如何找到给定数字列表的所有加法变体 - Python

How to find all variations of addition given a list of numbers - Python

假设我有一个数字列表 [2,8,16] 并且我想从中找到我可以拥有的所有唯一总和(在这种情况下它们将是:2,8,16,10,18,24,26

在 Python3 中有没有简单的方法可以做到这一点?

这是通过 itertools.combinations 的一种方式。

from itertools import combinations

lst = [2, 8, 16]

result = sorted({sum(i) for j in range(1, len(lst)+1) for i in combinations(lst, j)})
# [2, 8, 10, 16, 18, 24, 26]

讲座: chainchain.from_iterablecombinations

带有被加数输出的部分和:

import itertools
nums = [2,8,16]

sums = itertools.chain( itertools.combinations(nums, r=n) for n in range(1,len(nums)+1))

for it in  sums:
    for s in it:
        print ( f"sum({s}) = {s if isinstance(s,int) else sum(s)}")

输出:

sum((2,)) = 2
sum((8,)) = 8
sum((16,)) = 16
sum((2, 8)) = 10
sum((2, 16)) = 18
sum((8, 16)) = 24
sum((2, 8, 16)) = 26

无聊的一个是:

sums = itertools.chain( itertools.combinations(nums, r=n) for n in range(1,len(nums)+1))
print( [sum(s) for it in sums for s in it])        

输出:

[2, 8, 16, 10, 18, 24, 26]

你可以通过研究找到的 itertools-recipes: powerset:

from itertools import chain, combinations 
nums = [2,8,6,16]

def powerset(iterable):
    """powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)

     Credit to: https://docs.python.org/3/library/itertools.html#itertools-recipes"""
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

print( sorted([sum(s) for s in powerset(nums) if s])) #sorted + remove empty tuple

输出:

[2, 6, 8, 8, 10, 14, 16, 16, 18, 22, 24, 24, 26, 30, 32]

Sidenote: these solutions will conserve duplicate sums. Put them in list(set(result)) to remove duplicates, maybe using sorted() to order them. This was not part of the original question but added as comment to the accepted answer.