需要所有加起来等于x的组合
a = [1, +0, -6, 2, 3, 1, -0, 1, 2, -6, 9]
x = 3
输出:如.
1,2
1,1,1
我不认为Numpy或Pandas会特别有帮助,但这里有一个简单的Python方法,应该是相当有效的。它不保留原始数字的顺序。
注意,这将只报告一次相同的组合,即使有多种方法使它(例如,(1, 2)
)。这符合你的例子。并将+0
和-0
处理为0
。
a = [1, +0, -6, 2, 3, 1, -0 , 1, 2, -6, 9]
x = 3
def find_sums(lst, total):
"""
Report all permutations of items in `lst` that add up to `total`.
`lst` must be sorted.
"""
print(f"called with {lst}, {total}")
results = set()
for i, v in enumerate(lst):
if v > total:
# no more solutions possible; return what we have
break
elif v == total:
# v will finish a series, but we don't stop in case there are
# zeroes later
results.add((v,))
else:
# find all possible solutions starting with the current `v`
results.update(
(v,) + c
for c in find_sums(lst[(i+1):], total-v)
)
return results
print(find_sums(sorted(a), x))
# {
# (-6, 0, 0, 1, 1, 2, 2, 3),
# (-6, -6, 0, 1, 1, 1, 3, 9),
# (-6, 0, 9),
# (-6, -6, 0, 0, 1, 1, 2, 2, 9),
# (-6, 0, 1, 1, 2, 2, 3),
# (0, 0, 1, 1, 1),
# (-6, -6, 0, 0, 1, 2, 3, 9),
# (0, 1, 2),
# (-6, 9),
# (-6, -6, 1, 2, 3, 9),
# (1, 2),
# (0, 0, 3),
# (-6, 1, 1, 2, 2, 3),
# (-6, 0, 0, 9),
# (-6, -6, 1, 1, 1, 3, 9),
# (3,),
# (-6, -6, 0, 0, 1, 1, 1, 3, 9),
# (-6, -6, 1, 1, 2, 2, 9),
# (-6, -6, 0, 1, 1, 2, 2, 9),
# (0, 1, 1, 1),
# (0, 3),
# (0, 0, 1, 2),
# (-6, -6, 0, 1, 2, 3, 9),
# (1, 1, 1)
# }