Find Product Of Any Subset Of Elements From A List
what is the best way to find the product of any number of elements from a list? e.g if I have [a,b,c] as the input, i should get [a,b,c,a*b,a*c,b*c,a*b*c] as the output (order of e
Solution 1:
Here you go:
from itertools import combinations
l = [2, 3, 5]
result = []
for i inrange(1, len(l) + 1):
result += list(combinations(l, i))
multiplied_result = [reduce(lambda x, y: x*y, lst) for lst in result]
Now if we print the result, we get
>>>print listmap
[2, 3, 5, 6, 10, 15, 30]
Solution 2:
You can use itertools.combinations
within a list comprehension :
>>>deffind_mul(li):...return [[reduce(lambda x,y:x*y,j) for j in combinations(li,i)] for i in xrange(2,len(li)+1)]...
DEMO:
>>> [list(combinations([2,3,4],i)) for i in xrange(2,len([2,3,4])+1)]
[[(2, 3), (2, 4), (3, 4)], [(2, 3, 4)]]
>>> l=[2,3,4]
>>> find_mul(l)
[[6, 8, 12], [24]]
Post a Comment for "Find Product Of Any Subset Of Elements From A List"