[英]Finding all possible permutations of an unfixed length of numbers to reach a given sum or product
[英]Finding all possible permutations of a fixed length of numbers to reach a given sum
我想修改subset_sum()
python 函數從查找所有可能的數字組合以達到給定的總和,以便:
我已經成功完成了#2,但我需要#1 的幫助:
def subset_sum(numbers, target, length, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target and len(partial) == length:
print(f"sum({partial})={target}")
if s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, length, partial + [n])
所需的輸出應該是:
>>> subset_sum([3,9,8,4,5,7,10],target=15,length=3)
sum([3, 8, 4])=15
sum([3, 4, 8])=15
sum([4, 3, 8])=15
sum([4, 8, 3])=15
sum([8, 3, 4])=15
sum([8, 4, 3])=15
sum([3, 5, 7])=15
sum([3, 7, 5])=15
sum([5, 3, 7])=15
sum([5, 7, 3])=15
sum([7, 3, 5])=15
sum([7, 5, 3])=15
既然你已經解決了識別每個等價組中的一個解決方案的問題,我的建議是:不要改變該算法。 相反,利用itertools.permutations
來生成這些項目:
return list(itertools.permutations(numbers))
這樣做:
import itertools
numbers = [3,9,8,4,5,7,10]
length = 3
target = 15
iterable = itertools.permutations(numbers,length)
predicate = lambda x: (sum(x) == target)
vals = filter(predicate,iterable)
list(vals)
或單線:
vals = [x for x in itertools.permutations(numbers,length) if sum(x) == target]
結果:
[(3, 8, 4),
(3, 4, 8),
(3, 5, 7),
(3, 7, 5),
(8, 3, 4),
(8, 4, 3),
(4, 3, 8),
(4, 8, 3),
(5, 3, 7),
(5, 7, 3),
(7, 3, 5),
(7, 5, 3)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.