如何在python中列出所有将数字列表加总到N的方法(带重复项)?

时间:2017-09-03 21:46:35

标签: python algorithm

我有一个数字列表,比方说,     [2,4,5,6,7]

我想列出所有这些数字的唯一方式,可以将这些数字合并为N,并重复。

例如,如果N为8.答案将是:

2+2+2+2
4+4
6+2
4+2+2

订单无关紧要。

我最接近的是这个问题的答案: Finding all possible combinations of numbers to reach a given sum

def subset_sum(numbers,target,partial = []):     s =总和(部分)

# check if the partial sum is equals to target
if s == target: 
    print "sum(%s)=%s" % (partial, target)
if s >= target:
    return  # if we reach the number why bother to continue

for i in range(len(numbers)):
    n = numbers[i]
    remaining = numbers[i+1:]
    subset_sum(remaining, target, partial + [n]) 


if __name__ == "__main__":
    subset_sum([3,9,8,4,5,7,10],15)

#Outputs:
#sum([3, 8, 4])=15
#sum([3, 5, 7])=15
#sum([8, 7])=15
#sum([5, 10])=15

如何修改此项以允许重复?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

import itertools

data = [itertools.product([2,4,5,6,7], repeat = i) for i in range(2, 5)]

new_data = [[b for b in i if sum(b) == 8] for i in data]

print(len(list(itertools.chain.from_iterable(new_data))))