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).
I currently have:
# 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
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.
itertools.permutationsfunction, becausecombinations(seq, len(seq))has only 1 element, theseqitself. From the doc tocombinations: Return r length subsequences of elements from the input iterable. There is only 1 subsequence with the length of the whole sequence and that is the sequence itself.