![](/img/trans.png)
[英]Find the numbers that can be made with addition and subtraction, using all numbers given
[英]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]
讲座: 链与链 。from_iterable及其组合
部分和与求和的输出:
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()
对其进行sorted()
。 这不是原始问题的一部分,而是作为对已接受答案的注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.