在Python 3中迭代求和组合 [英] Iterate through sum combinations in Python 3
问题描述
我正在寻找一种方法,以求和的总和与斐波那契数列的元素的所有组合的给定极限等于相同的值.我知道itertools
中的combinations()
是解决此类问题的最佳选择,但由于我是Python新手,所以我想知道如何保留匹配的组合(因为只有一种是正确的,因为这不是正确的).算法的结尾).
I'm look for a way to find all combinations of sums with elements of a Fibonacci sequence with a given limit which equal that same value. I know that combinations()
from itertools
is our best bet in solving such problems, but as I'm new in Python I like to know how I can retain the matching combinations (as only one is correct, as this is not the end of the algorithm).
我目前有:
# Call Fibonacci sequence with a given limit:
def fib1(n):
result = []
a, b = 1, 1
while a < n:
result.append(a)
a, b = b, a + b
return result
# Wrong code, skeleton:
def zeckendorf(n):
from itertools import combinations
seq = fib1(n)
row = []
sum = 0
for i in combinations(seq, len(seq)):
sum += i
row.append(i)
if sum > n:
sum = 0
row = []
continue
elif sum == n:
break
return row
现在我知道第二点在很多方面是错误的.另外,我尝试将元组添加到整数时犯了一个错误.我只需要知道如何使用itertools模块分别遍历那些组合的各个元素.只有总和为'n'的组合对我有用.
Now I know the second bit is wrong in many ways. Also, I make the mistake as to try to add tuples to integers. I just need to know how I can iterate through separate elements of those combinations separately using the itertools module. Only the combinations with sum 'n' are useful to me.
推荐答案
要查找具有所需总和的 all 组合,请将每个组合附加到结果列表中:
To find all the combinations with the desired sum, append each combination to a result list:
def combinations_with_sum(sequence, desired_sum):
results = []
for i in range(len(sequence)):
results.extend([combination for combination in combinations(sequence, i)
if sum(combination) == desired_sum])
return results
这篇关于在Python 3中迭代求和组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!