Search code examples
pythoncombinationsmultiplication

How to get all possible combinations of a list’s elements(with limiting elements combinations) and multiple it?


I want to multiply each combination of elements in a list, and store it in the same list, for example:

A=[0,1,3,5,7]

#generate this combination (only A[1]:A[3])
A[5]=A[1]*A[2] # 1x3=3
A[6]=A[1]*A[3] # 1x5=5
A[7]=A[2]*A[3] # 3x15=15

Then I want the output of to be

A=[0,1,3,5,7,3,5,15]

How do I get this done?


Solution

  • As @Patrick suggests, you can use itertools.combinations first:

     comb = list(itertools.combinations(A[1:4], 2))
    

    And then extend your list as follows:

    A.extend([cc[0] * cc[1] for cc in comb])