求数字元素的和以获得所需结果

2024-09-29 21:44:48 发布

您现在位置:Python中文网/ 问答频道 /正文

通过使用代码段

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)]

结果的所有元素不需要包含在数字组合中

编辑:

1解决方案

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)

Tags: inforif代码段数字resultsseqprint
1条回答
网友
1楼 · 发布于 2024-09-29 21:44:48

我建议使用一个递归函数,它将首先找到最大的组合,然后使用剩余的数字调用自己,以添加与结果匹配的其他组合

此外,除了数字本身,还应使用索引生成组合,以便在列表包含重复数字时更容易确定剩余值

from itertools import combinations

def comboToSums(numbers,results,size=None):
    if size is None: size = len(numbers)
    if size == 0: return []
    for combo in combinations(enumerate(numbers),size):
        indexes,values = zip(*combo)
        if sum(values) not in results: continue
        remaining = [n for i,n in enumerate(numbers) if i not in indexes]
        return [values] + comboToSums(remaining,results)
    return comboToSums(numbers,results,size-1)

输出:

numbers = [1,2,3,4,5]
results = [7,8]
c = comboToSums(numbers,results)
print(c) # [(1, 2, 4), (3, 5)]

相关问题 更多 >

    热门问题