通过使用代码段
import itertools
numbers = [1,2,3,4,5]
results = [7,8]
allcombs = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) in results]
print(allcombs)
我能得到所有的组合,这些组合给了我渴望的结果。这里的主要问题是这个数字不能重复。所以,不是结果
[(1, 2, 4), (1, 2, 5), (1, 3, 4), (2, 5), (3, 4), (3, 5)]
我需要去
[(1, 2, 4),(3, 5)]
结果的所有元素不需要包含在数字组合中
编辑:
usednumbers = []
newresult = []
for comb in allcombs:
if not any(a in usednumbers for a in comb):
newresult.append(comb)
for n in comb:
usednumbers.append(n)
print(newresult)
我建议使用一个递归函数,它将首先找到最大的组合,然后使用剩余的数字调用自己,以添加与结果匹配的其他组合
此外,除了数字本身,还应使用索引生成组合,以便在列表包含重复数字时更容易确定剩余值
输出:
相关问题 更多 >
编程相关推荐