Skip to content Skip to sidebar Skip to footer

Calculate Fibonacci Numbers Up To At Least N

I am trying to make a function that allows a user to input a number and the result will be a list containing Fibonacci numbers up to the input and one above if the input is not in

Solution 1:

A possible solution is the following

def fibo_up_to(n):
    if n < 2:
        return [1,1]
    else:
        L = fibo_up_to(n-1)
        if L[-1] < n:
            L.append(L[-1] + L[-2])
        return L

the idea is that to return the list of all fibonacci numbers less than n you can ask for the list of those less than n-1 and then possibly add just one element. This works from 2 on if we define the first two numbers being [1, 1]. Using [0, 1] instead creates a problem for 2 because a single next element is not enough.

This code is not inefficient on time (fibonacci is a double recursion, this is a simple recursion), but uses a lot of stack space.

Solution 2:

 def calculate_fibonnaci(n):
     ifn== 0:
         return0ifn== 1:
         return1else:
         return calculate_fibonnaci(n - 1) + calculate_fibonnaci(n - 2)

Here's a simple solution using a recursive function.

Post a Comment for "Calculate Fibonacci Numbers Up To At Least N"