I was curious about how I can implement the Fibonacci sequence for summing the last n elements instead of just the last 2. So I was thinking about implementing a function nBonacci(n,m) where n is the number of last elements we gotta sum, and m is the number of elements in this list.
The Fibonacci sequence starts with 2 ones, and each following element is the sum of the 2 previous numbers.
Let’s make a generalization: The nBonacci sequence starts with n ones, and each following element is the sum of the previous n numbers.
I want to define the nBonacci function that takes the positive integer n and a positive integer m, with m>n, and returns a list with the first m elements of the nBonacci sequence corresponding to the value n.
For example, nBonacci(3,8) should return the list [1, 1, 1, 3, 5, 9, 17, 31].
def fib(num):
a = 0
b = 1
while b <= num:
prev_a = a
a = b
b = prev_a +b
The problem is that I don’t know the number of times I gotta sum. Does anyone have an idea and a suggestion of resolution?
>Solution :
The nBonacci sequence will always have to start with n ones, or the sequence could never start. Therefore, we can just take advantage of the range() function and slice the existing list:
def nfib(n, m):
lst = [1] * n
for i in range(n, m):
lst.append(sum(lst[i-n:i]))
return lst
print(nfib(3, 8)) # => [1, 1, 1, 3, 5, 9, 17, 31]