Python Program to Print Fibonacci Using Recursion
def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2) and then calling it in a loop to print the sequence.Examples
How to Think About It
Algorithm
Code
def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) n = 5 for i in range(n): print(fibonacci(i), end=' ')
Dry Run
Let's trace fibonacci(4) through the code
Call fibonacci(4)
Since 4 > 1, call fibonacci(3) + fibonacci(2)
Call fibonacci(3)
Since 3 > 1, call fibonacci(2) + fibonacci(1)
Call fibonacci(2)
Since 2 > 1, call fibonacci(1) + fibonacci(0)
Call fibonacci(1)
Return 1 (base case)
Call fibonacci(0)
Return 0 (base case)
Return from fibonacci(2)
1 + 0 = 1
Call fibonacci(1)
Return 1 (base case)
Return from fibonacci(3)
1 + 1 = 2
Call fibonacci(2)
Return 1 (from previous calculation)
Return from fibonacci(4)
2 + 1 = 3
| Function Call | Returned Value |
|---|---|
| fibonacci(0) | 0 |
| fibonacci(1) | 1 |
| fibonacci(2) | 1 |
| fibonacci(3) | 2 |
| fibonacci(4) | 3 |
Why This Works
Step 1: Base Case
The function returns n directly when n is 0 or 1, stopping the recursion.
Step 2: Recursive Calls
For other values, the function calls itself twice with n-1 and n-2 to get the two previous Fibonacci numbers.
Step 3: Summing Results
It adds the results of these two calls to find the Fibonacci number for n.
Alternative Approaches
def fibonacci_iter(n): a, b = 0, 1 for _ in range(n): print(a, end=' ') a, b = b, a + b fibonacci_iter(5)
def fibonacci_memo(n, memo={}): if n in memo: return memo[n] if n <= 1: memo[n] = n else: memo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2, memo) return memo[n] n = 5 for i in range(n): print(fibonacci_memo(i), end=' ')
Complexity: O(2^n) time, O(n) space
Time Complexity
The recursive Fibonacci function calls itself twice for each non-base case, leading to exponential growth in calls.
Space Complexity
The maximum depth of the recursion stack is n, so space is linear.
Which Approach is Fastest?
Iterative and memoized methods run in linear time O(n), much faster than simple recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple Recursion | O(2^n) | O(n) | Learning recursion basics |
| Memoization | O(n) | O(n) | Efficient recursion with caching |
| Iterative | O(n) | O(1) | Fastest and simplest for large inputs |