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

Question:

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?

Asked By: Vasco Ascensão

||

Answers:

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]
Answered By: Michael M.

Here is one way to implement a function that returns the terms of a generalized Fibonacci sequence, where n is the starting term and m is the number of terms to return:

def nBonacci(n, m):
    # Initialize the result list with the first n terms of the sequence
    result = [1] * n
    # Calculate the next m-n terms and append them to the result list
    for i in range(m - n):
        # The next term is the sum of the previous n terms
        next_term = sum(result[-n:])
        result.append(next_term)
    return result

Here is an example of how this function can be used:

# The first 8 terms of the sequence starting with 3 1's
print(nBonacci(3, 8))
# Output: [1, 1, 1, 3, 5, 9, 17, 31]

Note that this implementation is not optimized for large m, as the time complexity is O(m^2). For large m, a more efficient implementation would be needed.

Answered By: Jefferson

If you wanted to the fibonacci sequence recursively, you could do

def fib(x, y, l):
    if len(l) == y:
        return l
    return fib(x, y, l + [sum(l[-x:])])


num = 3
print(fib(num, 8, [1 for _ in range(num)])) #[1, 1, 1, 3, 5, 9, 17, 31]
Answered By: Chrome Tules
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.