Open In App

Print the Fibonacci sequence – Python

Last Updated : 22 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To print the Fibonacci sequence in Python, we need to generate a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci sequence follows a specific pattern that begins with 0 and 1, and every subsequent number is the sum of the two previous numbers.

Mathematically, the Fibonacci sequence can be represented as:

F(n) = F(n-1) + F(n-2)

Where:
F(0) = 0
F(1) = 1
F(n) for n > 1 is the sum of the two preceding numbers.

The sequence looks like this:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

Using Naive Approach

This approach uses a while loop to print the first n Fibonacci numbers by repeatedly summing the previous two numbers. It starts with 0 and 1, and calculates the next number in the sequence until n terms are printed.

Python
n = 10
a = 0
b = 1
next = b  
count = 1

while count <= n:
    print(next, end=" ")
    count += 1
    a, b = b, next
    next = a + b
print()

Output
1 2 3 5 8 13 21 34 55 89 

Explanation:

  • The code uses an iterative approach to print the first 10 numbers of the Fibonacci sequence, starting from 0 and 1.
  • It updates the values of a and b in each iteration and calculates the next Fibonacci number (next), printing each number in the sequence.

Optimization of Fibonacci sequence

This approach iteratively calculates the nth Fibonacci number by updating two variables, a and b, without recursion, making it more efficient in terms of time and space.

Python
def fibonacci(n):
    a = 0
    b = 1
    
    # Check if n is less than 0
    if n < 0:
        print("Incorrect input")
        
    # Check if n is equal to 0
    elif n == 0:
        return 0
      
    # Check if n is equal to 1
    elif n == 1:
        return b
    else:
        for i in range(1, n):
            c = a + b
            a = b
            b = c
        return b

print(fibonacci(9))

Output
34

Explanation:

  • The code calculates the nth Fibonacci number using an iterative approach, starting with 0 and 1.
  • It checks for invalid inputs and handles the cases where n is 0 or 1, and for larger n, it uses a loop to calculate the Fibonacci number by updating a and b in each iteration.

Using DP (Dynamic Programming)

This approach uses dynamic programming by storing previously computed Fibonacci numbers in a list (FibArray). It avoids redundant calculations by checking if the result is already available, making it more efficient than the naive recursive approach.

Python
FibArray = [0, 1]

def fibonacci(n):
  
    # Check is n is less than 0
    if n < 0:
        print("Incorrect input")
        
    # Check is n is less than len(FibArray)
    elif n < len(FibArray):
        return FibArray[n]
    else:        
        FibArray.append(fibonacci(n - 1) + fibonacci(n - 2))
        return FibArray[n]

print(fibonacci(9))

Output
34

Explanation:

  • The code calculates the nth Fibonacci number using dynamic programming by storing previously calculated values in FibArray.
  • It checks for invalid input, and if n is smaller than the length of FibArray.

Using Cache  

This approach uses Python’s lru_cache decorator from the functools module to cache the results of the Fibonacci function. It stores the results of expensive recursive calls, improving efficiency by avoiding redundant calculations, especially for larger values of n.

Python
from functools import lru_cache

@lru_cache(None)
def fibonacci(num: int) -> int:

    # check if num is less than 0 it will return none
    if num < 0:
        print("Incorrect input")
        return

    # check if num between 1, 0 it will return num
    elif num < 2:
        return num

    # return the fibonacci of num - 1 & num - 2
    return fibonacci(num - 1) + fibonacci(num - 2)

print(fibonacci(9))

Output
34

Explanation:

  • The code calculates the nth Fibonacci number using recursion with memoization, leveraging Python’s functools.lru_cache to store and reuse previously computed results.
  • It checks for invalid inputs, and for valid num, it recursively calculates the Fibonacci number by summing the results of the previous two terms, using the cache to optimize performance.

Using Backtracking

This approach uses backtracking with memoization to optimize the Fibonacci calculation. It stores previously computed values in a dictionary (memo), ensuring that each Fibonacci number is computed only once. This reduces the time complexity significantly compared to the naive recursive method.

Python
def fibonacci(n, memo={}):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    elif n in memo:
        return memo[n]
    else:
        memo[n] = fibonacci(n-1) + fibonacci(n-2)
        return memo[n]

print(fibonacci(9))

Output
34

Explanation:

  • The code calculates the nth Fibonacci number using recursion with memoization by storing previously computed values in a dictionary (memo).
  • It checks for base cases (n <= 0 and n == 1), and for other values, it computes the Fibonacci number recursively, storing the result in memo to avoid redundant calculations.

Using Recursion   

This approach uses recursion to calculate the Fibonacci sequence. The base cases handle inputs of 0 and 1 (returning 0 and 1 respectively). For values greater than 1, it recursively calls the function to sum the previous two Fibonacci numbers. While this method is straightforward, it is inefficient for larger inputs due to redundant calculations.

Python
def Fibonacci(n):

    if n < 0:
        print("Incorrect input")

    elif n == 0:
        return 0

    elif n == 1 or n == 2:
        return 1

    else:
        return Fibonacci(n-1) + Fibonacci(n-2)

print(Fibonacci(9))

Output
34

Explanation:

  • The code calculates the nth Fibonacci number using a recursive approach.
  • It checks for invalid inputs (n < 0), base cases (n == 0 or n == 1), and recursively calculates the Fibonacci number by summing the results of the previous two terms for larger n.

Please refer complete article on the Program for Fibonacci numbers for more details! 



Next Article
Article Tags :

Similar Reads