Fibonacci Sequence in Python | Code, Algorithm & Extra #Imaginations Hub

Fibonacci Sequence in Python | Code, Algorithm & Extra #Imaginations Hub
Image source -


The Fibonacci sequence in python is a mathematical sequence that begins with 0 and 1, with every subsequent quantity being the sum of the 2 previous ones. In Python, producing the Fibonacci sequence just isn’t solely a basic programming train but in addition a good way to discover recursion and iterative options.

  • F(0) = 0
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) for n > 1

What’s the Fibonacci Sequence?

The Fibonacci sequence is a sequence the place each quantity is the sum of the 2 numbers previous it, starting with 0 and 1. 

Supply: TecAdmin

Wish to Be taught Python for Free? Discover our Free Course At the moment!

Mathematical Components for the Fibonacci Sequence

The mathematical method to calculate the Fibonacci sequence is: 

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

The place:

  • F(n) is the nth Fibonacci quantity
  • F(n-1) is the (n-1)th Fibonacci quantity
  • F(n-2) is the (n-2)th Fibonacci quantity

Recursive Definition

The recursive definition of the Fibonacci sequence relies on the recursive system.

  • F(0) = 0
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) for n > 1

So, each quantity within the Fibonacci sequence is calculated by together with the 2 numbers  earlier than it. This recursive technique continues producing the whole sequence, ranging from  0 and 1.

Additionally Learn: Prime 10 Makes use of of Python within the Actual World with Examples

Recursive Fibonacci Sequence in Python

Fibonacci numbers recursively in Python utilizing recursive options. Right here’s a Python code  to calculate the nth Fibonacci quantity through the use of recursion:

Def fibonacci(n):
    if n <= 0:
        return 0 
    elif n == 1:
        return 1
        return fibonacci(n-1) + fibonacci (n-2)
#import csv

Iterative Fibonacci Sequence in Python,

An iterative technique to calculate Fibonacci numbers in Python, includes utilizing loops to construct the sequence iteratively. 

Iterative Fibonacci Algorithm in Python:

def fibonacci_iterative(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
        fib_prev = 0  # Initialize the primary Fibonacci quantity
        fib_current = 1  # Initialize the second  Fibonacci quantity
        For _ in vary(2, n + 1):
            fib_next = fib_prev + fib_current  # Calculate the following Fibonacci quantity
            fib_prev, fib_current = fib_current, fib_next  # Replace values for the following iteration 
        return fib_current
#import csv

Comparability with the Recursive Strategy

Distinction foundation Recursive Strategy Iterative Strategy
Effectivity This method is extra environment friendly for giant “n” values, calculating the Fibonacci numbers iteratively and with out redundant calculations. This method is much less environment friendly, particularly for giant “n” because it causes redundant calculations.
Time Complexity 0(n) (Linear) 0 (2^n) (Exponential) 
Area Complexity 0(1) (Fixed)  0(n) (Linear) 

Memoization for Environment friendly Calculation

Memoization is a technique that speeds laptop applications or algorithms by storing the outcomes of pricy operate calls and returning the cached consequence when the identical inputs happen once more. It’s helpful in optimizing Fibonacci calculations because the recursive method recalculates the identical Fibonacci numbers many instances, resulting in inefficiency.

How Memoization Reduces Redundant Calculations

In Fibonacci calculations, with out memoization, the recursive algorithm recalculates the identical numbers time and again .Memoization fixes this challenge by storing the outcomes. When the operate is known as once more with the identical enter, it makes use of the calculated consequence for the issue.

Implementing Memoization in Python for Fibonacci

Right here’s the way you implement  memoization in Python to optimize Fibonacci calculations:

# Create a dictionary to retailer computed Fibonacci numbers.
Fib_cache = 
def fibonacci_memoization(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1

    # Examine if the result's already throughout the cache.
    If n in fib_cache:
        return fib_cache[n]

    # If not, calculate it recursively and retailer it within the cache.
    fib_value = fibonacci_memoization(n - 1) + fibonacci_memoization(n - 2)
    fib_cache[n] = fib_value

    return fib_value
#import csv

Dynamic Programming for Python Fibonacci Sequence

Dynamic programming is a method used to resolve issues by breaking them down into smaller subproblems and fixing every subproblem solely as soon as, storing the outcomes to keep away from redundant calculations. This method may be very efficient for fixing complicated issues like calculating Fibonacci numbers efficiently.

Clarification of the Dynamic Programming Strategy to Fibonacci:

Dynamic programming includes storing Fibonacci numbers in an array or dictionary once they’re calculated in order that they are often reused each time wanted. As a substitute of recalculating the identical Fibonacci numbers, dynamic programming shops them as soon as and retrieves them as wanted.

The dynamic programming method can be utilized with both an array or a dictionary (hash desk) to retailer intermediate Fibonacci numbers. 

def fibonacci_dynamic_programming(n):
    fib = [0] * (n + 1)  # Initialize an array to retailer Fibonacci numbers.
    Fib[1] = 1  # Set the bottom circumstances.
    For i in vary(2, n + 1):
        fib[i] = fib[i - 1] + fib[i - 2]  # Calculate and retailer the Fibonacci numbers.
    Return fib[n]  # Return the nth Fibonacci quantity.
#import csv

Advantages of Dynamic Programming in Phrases of Time Complexity

The dynamic programming technique for calculating Fibonacci numbers provides a number of benefits by way of time complexity:

Lowered Time Complexity: Dynamic programming reduces the time complexity of Fibonacci calculations from exponential (O(2^n)) within the naive recursive method to linear (O(n)).

Environment friendly Reuse: By storing intermediate outcomes, dynamic programming avoids redundant calculations. Every Fibonacci quantity is calculated as soon as after which retrieved from reminiscence as and when wanted, enhancing effectivity.

Improved Scalability: The dynamic programming technique stays environment friendly even for large values of “n,” making it acceptable for sensible purposes.

Area Optimization for Fibonacci

Area optimization methods for calculating Fibonacci numbers goal to cut back reminiscence utilization by storing solely the vital earlier values somewhat than the whole sequence. These strategies are particularly helpful when reminiscence effectivity is a priority.

Utilizing Variables to Retailer Solely Needed Earlier Values

One of the repeatedly used space-optimized methods for Fibonacci is to use variables to retailer solely the 2 most up-to-date Fibonacci numbers somewhat than an array to retailer the whole sequence. 

def fibonacci_space_optimized(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1

    fib_prev = 0  # Initialize the previous Fibonacci quantity.
    Fib_current = 1  # Initialize the present Fibonacci quantity.

    For _ in selection(2, n + 1):
        fib_next = fib_prev + fib_current  #Calculate the following Fibonacci quantity.
        fib_prev, fib_current = fib_current, fib_next  # Replace values for the following iteration.

    Return fib_current  # Return the nth Fibonacci quantity.

#import csv

Commerce-offs Between Area and Time Complexity

Area-optimized strategies for Fibonacci include trade-offs amongst area and time complexity:

Area Effectivity: Area-optimized approaches use a lot much less reminiscence as a result of they retailer just a few variables (usually two) to maintain observe of the most recent Fibonacci numbers. That is comparatively space-efficient, making it appropriate for memory-constrained environments.

Time Effectivity: Whereas these methods are usually not linear (O(n)) by way of time complexity, they could be barely slower than dynamic programming with an array due to the variable assignments. Nonetheless, the distinction is often negligible for sensible values of “n”.

Producing Fibonacci Numbers as much as N

Producing Fibonacci numbers as much as N Python could be performed with a loop. Right here’s a Python code  that generates Fibonacci numbers as much as N:

def generate_fibonacci(restriction):
    if restrict <= 0:
        return []

    fibonacci_sequence = [0, 1]  # Initialize with the primary two Fibonacci numbers.
    Whereas True:
        next_fib = fibonacci_sequence[-1] + fibonacci_sequence[-2]
        if next_fib > restriction:
    return fibonacci_sequence
#import csv

Purposes of Producing Fibonacci Sequences inside a Vary

  • Quantity Sequence Evaluation: Producing Fibonacci numbers inside a restrict could be helpful for analyzing and learning quantity sequences, figuring out patterns, and exploring mathematical properties.
  • Efficiency Evaluation: In laptop science and algorithm analysis, Fibonacci sequences can be utilized to investigate the efficiency of algorithms and knowledge construction, primarily by way of time and area complexity.
  • Utility Testing: In software testing, Fibonacci numbers could also be used to create take a look at circumstances with various enter sizes to evaluate the efficiency and robustness of software program purposes.
  • Monetary Modeling: Fibonacci sequences have purposes in monetary modeling, particularly in learning market tendencies and value actions in fields like inventory buying and selling and funding evaluation.

Fibonacci Sequence Purposes

The Fibonacci sequence has many real-world purposes. In nature, it describes the association of leaves, petals, and seeds in vegetation, exemplifying environment friendly packing. The Golden Ratio derived from Fibonacci proportions is used to create aesthetically fascinating compositions and designs. In know-how, Fibonacci numbers play a task in algorithm optimization, similar to dynamic programming and memoization, enhancing efficiency in tasks like calculating large Fibonacci values or fixing optimization issues. Furthermore, Fibonacci sequences are utilized in monetary modeling, aiding in market evaluation and predicting value tendencies. These real-world purposes underscore the importance of the Fibonacci sequence in arithmetic, nature, artwork, and problem-solving.

Fibonacci Golden Ratio

The Fibonacci Golden Ratio, usually denoted as Phi (Φ), is an irrational vary roughly equal to 1.61803398875. This mathematical fixed is deeply intertwined with the Fibonacci sequence. As you progress within the Fibonacci sequence, the ratio amongst consecutive Fibonacci more and more approximates Phi. This connection provides rise to aesthetic rules in design, the place parts are sometimes proportioned to Phi, creating visually harmonious compositions. Sensible examples embody the structure of the Parthenon, art work just like the Mona Lisa, and the proportions of the human face, highlighting the Golden Ratio’s intensive use in attaining aesthetically fascinating and balanced designs in quite a few fields, from artwork and structure to graphic and internet design.

Fibonacci in Buying and selling and Finance

Fibonacci performs an important position in buying and selling and finance by way of Fibonacci retracement and extension ranges in technical evaluation. Merchants use these ranges to establish potential help and resistance factors in monetary markets. The Fibonacci sequence helps in predicting inventory market tendencies by figuring out key value ranges the place reversals or extensions are possible. Fibonacci buying and selling strategies contain utilizing these ranges at the side of technical indicators to make educated buying and selling choices. Merchants repeatedly search for Fibonacci patterns,  just like the Golden Ratio, to assist assume value actions. 


Whereas seemingly rooted in arithmetic, the Fibonacci sequence additionally has relevance in knowledge science. Understanding the rules of sequence era and sample recognition inherent within the Fibonacci sequence can help knowledge scientists in recognizing and analyzing recurring patterns inside datasets, a basic facet of knowledge evaluation and predictive modeling in knowledge science.. Enroll in our free Python course to advance your python abilities.

Steadily Requested Questions

Q1. What’s the Fibonacci sequence?

A. The Fibonacci sequence is a sequence of numbers that begins with 0 and 1, during which each subsequent quantity is the sum of the 2 earlier ones

Q2. What’s the method of the Fibonacci Sequence?

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

Q3. What’s the Fibonacci sequence of 5?

A. The Fibonacci sequence as much as the fifth quantity is: 0, 1, 1, 2, 3. So, the Fibonacci quantity is 3.

This fall. What are the primary 20 Fibonacci sequence

A. The primary 20 Fibonacci sequence are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, and 4181.

Related articles

You may also be interested in