Fibonacci Sequence – Python

The task is to generate the first N numbers in the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each is the sum of the two preceding ones, usually starting with 0 and 1.

We will implement three ways to find the Fibonacci Sequence in Python. Let’s explore:

Recursive Method

The recursive approach defines a function that calls itself to compute the Fibonacci numbers.

The base cases handle scenarios where N is less than or equal to 2. For larger values of N, the function appends the sum of the last two numbers in the sequence to the list returned by the recursive call.

def fibonacci_recursive(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        fib_sequence = fibonacci_recursive(n - 1)
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
        return fib_sequence

# Example usage
N = 10
print("Fibonacci Sequence (Recursive):", fibonacci_recursive(N))

Iterative Method

The iterative approach uses a loop to build the Fibonacci sequence. It initializes a list with the first two Fibonacci numbers and then iteratively appends the sum of the last two numbers until it reaches the desired length.

This method is efficient and straightforward, making it suitable for generating larger sequences.

def fibonacci_iterative(n):
    if n <= 0:
        return []
    fib_sequence = [0, 1]
    for i in range(2, n):
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence[:n]

# Example usage
N = 10
print("Fibonacci Sequence (Iterative):", fibonacci_iterative(N))

Memoization Method

The memoization technique optimizes the recursive approach by storing previously computed Fibonacci numbers in a dictionary. This prevents redundant calculations, significantly improving performance for larger values of N.

The function checks if the result for a given N is already in the memo dictionary before performing any calculations.

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

# Example usage
N = 10
print("Fibonacci Sequence (Memoization):", fibonacci_memoization(N))

Wrapping Up

In summary, each method has its advantages and use cases. The recursive method is simple but inefficient for large N, the iterative method is efficient and easy to understand, and the memoization method combines the elegance of recursion with the efficiency of caching results.