如何在给定数字列表的情况下找到添加的所有变体 - Python

时间:2018-01-31 18:27:09

标签: python python-3.x addition

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

我能用Python3轻松完成这项工作吗?

2 个答案:

答案 0 :(得分:3)

以下是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]

答案 1 :(得分:0)

讲座: 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]
  

旁注:这些解决方案将节省重复的金额。将它们放入list(set(result))以删除重复项,可以使用sorted()对它们进行排序。这不是原始问题的一部分,而是作为对已接受答案的评论。