Given a number n, the task is to print the Fibonacci sequence up to n terms. In the Fibonacci sequence, each number is the sum of the previous two numbers, starting from 0 and 1. For Example:
Input: n = 7
Output: 0 1 1 2 3 5 8
Let's explore different methods to print the Fibonacci sequence in Python.
Using an iterative approach
This approach generates the Fibonacci sequence by storing the previous two numbers and updating them in each iteration. Each new number is calculated by adding the last two Fibonacci numbers.
n = 7
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
Output
0 1 1 2 3 5 8
Explanation:
- a, b = 0, 1 initializes the first two Fibonacci numbers and for _ in range(n) runs the loop n times.
- print(a, end=" ") prints the current Fibonacci number and a, b = b, a + b updates the values for the next iteration.
Using Recursion
This approach calculates Fibonacci numbers by recursively calling the function for the previous two terms.
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
for i in range(7):
print(fib(i), end=" ")
Output
0 1 1 2 3 5 8
Explanation:
- if n <= 1 handles the base cases for 0 and 1.
- fib(n - 1) + fib(n - 2) recursively calculates the Fibonacci number.
- for i in range(7) prints the first 7 Fibonacci numbers.
Using Dynamic Programming
This approach stores previously calculated Fibonacci numbers in a list. Instead of recalculating values again and again, it reuses stored results to generate the sequence.
n = 7
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i - 1] + fib[i - 2])
print(*fib)
Output
0 1 1 2 3 5 8
Explanation:
- fib = [0, 1] stores the starting Fibonacci numbers and fib.append() adds the next Fibonacci number to the list.
- fib[i - 1] + fib[i - 2] calculates the next term using previous values and print(*fib) prints all Fibonacci numbers from the list.
Using functools.lru_cache
This approach uses caching to store previously computed Fibonacci values during recursion. When the same value is needed again, it is directly taken from the cache instead of recalculating it.
from functools import lru_cache
@lru_cache(None)
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
for i in range(7):
print(fib(i), end=" ")
Output
0 1 1 2 3 5 8
Explanation:
- @lru_cache(None) stores previously calculated Fibonacci values and if n <= 1 handles the base cases.
- fib(n - 1) + fib(n - 2) recursively calculates the Fibonacci number.
- Cached values are reused when the same calculation appears again.