Thursday, July 25, 2024

Nitheen Kumar

Generate the Fibonacci sequence up to a certain number of terms in Python

To generate the Fibonacci sequence up to a certain number of terms in Python, you can use a straightforward approach using either iteration or recursion. Here's how you can implement both methods:

  1. Using Iteration:
def generate_fibonacci_iterative(n):
    # Initialize the first two terms of the sequence
    fibonacci_sequence = [0, 1]
    
    # Generate Fibonacci sequence iteratively
    for i in range(2, n):
        next_term = fibonacci_sequence[-1] + fibonacci_sequence[-2]
        fibonacci_sequence.append(next_term)
        
    return fibonacci_sequence

  1. Using Recursion:
def generate_fibonacci_recursive(n):
    # Base case: handle the first two terms directly
    if n == 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    
    # Recursive case: generate Fibonacci sequence
    fibonacci_sequence = generate_fibonacci_recursive(n - 1)
    fibonacci_sequence.append(fibonacci_sequence[-1] + fibonacci_sequence[-2])
    
    return fibonacci_sequence

Example Usage:

You can test both functions with different values of n to generate Fibonacci sequences:

num_terms = 10


# Using iterative approach

fibonacci_iter = generate_fibonacci_iterative(num_terms)

print(f"Fibonacci sequence (iterative) with {num_terms} terms:", fibonacci_iter)


# Using recursive approach

fibonacci_rec = generate_fibonacci_recursive(num_terms)

print(f"Fibonacci sequence (recursive) with {num_terms} terms:", fibonacci_rec)



Generate the Fibonacci sequence up to a certain number of terms in Python

Explanation:

  • Iterative Approach (generate_fibonacci_iterative function):

    • Initialize fibonacci_sequence with the first two terms [0, 1].
    • Use a for loop to generate subsequent terms up to n by adding the last two terms in fibonacci_sequence.
    • Append each computed term to fibonacci_sequence until the sequence reaches n terms.
  • Recursive Approach (generate_fibonacci_recursive function):

    • Base cases handle sequences with 0, 1, or 2 terms directly.
    • For n > 2, recursively call the function to generate the Fibonacci sequence for n-1 terms.
    • Append the next Fibonacci number (fibonacci_sequence[-1] + fibonacci_sequence[-2]) to the generated sequence and return it.

Both methods are valid for generating the Fibonacci sequence up to n terms. The iterative approach is generally more efficient and easier to understand for this specific task. However, the recursive approach demonstrates the concept of recursion and can be useful in understanding recursive patterns.


Subscribe to get more Posts :