没有代表的可能数量达到给定数量

时间:2018-06-03 18:44:34

标签: python list sum combinations

我有一个任务,我需要计算所有可能的总和,直到给定的数字。例如:

mass_list = [4, 1, 8] 

和最大总和值为10 mass = 10

输出需要像>>>[1, 4, 5, 8, 9] 5(1 + 4)和9(8 + 1)

到目前为止,我想出了这个

quantity, mass = map(int,input().split())
mass_list = []
for x in range(1, 2):
    mass_list.extend(input().split(' '))
mass_list = list(map(int, mass_list))
count = len(mass_list)

感谢任何有关解决方案的帮助

2 个答案:

答案 0 :(得分:0)

from itertools import combinations

max_val = 10
results = []
for i in range(1, len(mass_list)):
    results.extend(
        [sum(c) for c in combinations(mass_list, i) if sum(c) < max_val]
    )

results
[4, 1, 8, 5, 9]

(灵感来自this answer

答案 1 :(得分:0)

使用itertools

import itertools

mass_list = [4, 1, 8]
mass = 10
output = []

for i in range(1, len(mass_list)):  # for each possible combination length
    for subset in itertools.combinations(mass_list, i):
       sum = 0
       for subset_element in subset:  # calculate sum of combination
          sum += subset_element
       if sum <= mass:  # do the check
          output.append(sum)

output.sort()
print(output)

打印:

[1, 4, 5, 8, 9]