Reputation: 23
I am trying to find a way to combine 2 lists and then sum the combined list in a specific way. The sum of the 2 previous elements must be summed to the next element.
Ex : the sum of the first combination, ((1, 2), (4,)) , should be (3,7,6), because 1+2=3, 3+4=7, 2+4=6.
And then be printed side by side : ((1, 2), (4,)) (3,7,6) IF it ( both the combination and its sum) do not contain a certain element ( somehow alredy inserted).
Here is my code and my examples:
a=[1,2,3]
b=[4,5,6]
import itertools
sets = [a,b];
ks = [2, 1,]
combinations = itertools.product(*[itertools.combinations(set, k) for set, k in zip(sets, ks)])
for combination in combinations:
print (combination)
Upvotes: 1
Views: 75
Reputation: 92854
Straight-forwardly:
for i in itertools.product(*[itertools.combinations(set, k) for set, k in zip(sets, ks)]):
i_sum = i[0][0] + i[0][1]
print(i, (i_sum, i_sum + i[1][0], i[0][1] + i[1][0]))
The output:
((1, 2), (4,)) (3, 7, 6)
((1, 2), (5,)) (3, 8, 7)
((1, 2), (6,)) (3, 9, 8)
((1, 3), (4,)) (4, 8, 7)
((1, 3), (5,)) (4, 9, 8)
((1, 3), (6,)) (4, 10, 9)
((2, 3), (4,)) (5, 9, 7)
((2, 3), (5,)) (5, 10, 8)
((2, 3), (6,)) (5, 11, 9)
Upvotes: 1