Kry*_*ton 6 python combinations sum list
我正在尝试在整数列表中找到一个总和的组合.
包含总和的数字量受变量限制,例如在列表中 -
[5,2,3,9,1],我想找到10的总和,只有2个数字.
这样程序就会打印出来[9,1].
我是python的新手,有一种简单的方法吗?
谢谢.
from itertools import combinations
l = [5,2,3,9,1]
for var in combinations(l, 2):
if var[0] + var[1] == 10:
print var[0], var[1]
Run Code Online (Sandbox Code Playgroud)
组合tuples从可迭代对象(可以循环的对象)创建所有可能的组合.让我来证明:
>>> [var for var in combinations([1,2,3,4,5], 2)]
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
>>> [var for var in combinations([1,2,3,4,5], 3)]
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
Run Code Online (Sandbox Code Playgroud)
暴力方法使用itertools.combinations:
In [6]: [pair for pair in itertools.combinations(li,2) if sum(pair) == 10]
Out[6]: [(9, 1)]
Run Code Online (Sandbox Code Playgroud)
这将为您提供总和为 10 的所有对。这在运行时是超指数的,因此如果您的输入很大,您将需要更复杂的算法。