Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute all products for all numbers in a python list [closed]

Tags:

python

Let's say that I have this list :

[2,3,5,7] 

I want to output all combinations of multiplication :

[6,10,14,15,21,35,30,42,105,210]

Is there a one liner in python for that?

like image 805
Maxime Roussin-Bélanger Avatar asked Jan 07 '23 19:01

Maxime Roussin-Bélanger


1 Answers

Assuming that you forgot the 70 in your output...

With numpy.prod and itertools.combinations:

>>> from numpy import prod
>>> from itertools import combinations
>>> lst = [2,3,5,7]
>>> [prod(x) for i in range(2, len(lst)+1) for x in combinations(lst, i)]
[6, 10, 14, 15, 21, 35, 30, 42, 70, 105, 210]
like image 195
timgeb Avatar answered Jan 20 '23 03:01

timgeb