[英]how to write a python code to calculate all the combination of given numbers that can sum up to a given number?
[英](python) How can i sum all the results of a combination in a specific way?
我試圖找到一種方法來組合 2 個列表,然后以特定方式對組合列表求和。 前兩個元素的總和必須與下一個元素相加。
例如:第一個組合 ((1, 2), (4,)) 的總和應該是 (3,7,6),因為 1+2=3, 3+4=7, 2+4=6 .
然后並排打印:((1, 2), (4,)) (3,7,6) 如果它(組合及其總和)不包含某個元素(不知何故已插入)。
這是我的代碼和示例:
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)
直截了當:
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]))
輸出:
((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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.