Python Program to Find Fibonacci Using Recursion
def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2) which calls itself to calculate previous Fibonacci numbers.Examples
How to Think About It
n, think of the sequence as starting with 0 and 1, and each next number is the sum of the two before it. Using recursion means the function calls itself with smaller numbers until it reaches the base cases where n is 0 or 1.Algorithm
Code
def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(10))
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)
Base case: return 1
Call fibonacci(0)
Base case: return 0
Return fibonacci(2)
1 + 0 = 1
Return fibonacci(1)
Base case: return 1
Return fibonacci(3)
1 + 1 = 2
Call fibonacci(2)
Call fibonacci(1) + fibonacci(0) = 1 + 0 = 1
Return fibonacci(4)
2 + 1 = 3
| Function Call | Returned Value |
|---|---|
| fibonacci(1) | 1 |
| fibonacci(0) | 0 |
| fibonacci(2) | 1 |
| fibonacci(1) | 1 |
| fibonacci(3) | 2 |
| fibonacci(2) | 1 |
| fibonacci(4) | 3 |
Why This Works
Step 1: Base Case
The function returns n directly if it 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 find the two previous Fibonacci numbers.
Step 3: Combining Results
It adds the results of these two calls to get the Fibonacci number for n.
Alternative Approaches
def fibonacci_iterative(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return a print(fibonacci_iterative(10))
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] print(fibonacci_memo(10))
Complexity: O(2^n) time, O(n) space
Time Complexity
The recursive 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 used is proportional to n.
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 |
| Iterative | O(n) | O(1) | Efficient calculation |
| Memoization | O(n) | O(n) | Efficient recursion with caching |