user6708727 user6708727 - 1 year ago 81
Python Question

Is there a way to do this in python?

I have a list of integers. For example [2,3,4] and I want to expand the list with outcomes of all possible multiplications of these integers. That would be in this case 6,8,12,24. How would I do this? Keep in mind that the list I want to do this with has 16 items so an algorithm for this case might not be a good solution for my case.

Answer Source

Here is a solution in basic Python (with only batteries included modules :-) ):

import itertools, functools

lst = [2,3,4]

comb = [itertools.combinations(lst, n) for n in range(2,  len(lst) + 1)]

lst2 = []
for gen in itertools.chain(*comb):
    lst2.append(functools.reduce(lambda x, y: x * y, list(gen)))



[6, 8, 12, 24]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download