Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implementing the Fibonacci sequence for the last n elements: The nBonacci sequence

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading