CAP7004 · Unit 1: Python foundations and analysis
Recursion
8 practice questions
Key points
- Needs a base case and progress toward it
- Each call uses a stack frame; default limit 1000
- Naive Fibonacci is exponential; memoize
- Hanoi needs 2^n - 1 moves
A recursive function solves a problem by calling itself on a smaller instance. Every recursion needs:
- a base case that stops the calls, and
- a recursive case that moves toward the base case.
def fact(n):
return 1 if n <= 1 else n * fact(n - 1)
Each call adds a stack frame. Python's default recursion limit is 1000; deeper recursion raises RecursionError. Missing or unreachable base cases cause infinite recursion.
Costs:
fact(n): n calls, O(n) time and O(n) stack space.- Naive
fib(n) = fib(n-1) + fib(n-2): exponential time (fib(10) makes 177 calls) because subproblems repeat; memoization fixes it. - Divide-by-2 recursion such as fast power
pw(x, n)or binary search: O(log n) calls. - Tower of Hanoi with n discs needs 2^n - 1 moves.
Recursion versus iteration: every recursion can be turned into a loop (possibly with an explicit stack); recursion is shorter for trees and divide-and-conquer.
Try two questions
Why is naive recursive Fibonacci slow?
- It has no base case
- It uses too many global variables
- Python cannot recurse twice per call
- It recomputes the same subproblems many times
Show the answer
D. Overlapping subproblems cause exponentially many calls (177 for fib(10)).
With fib(0)=0 and fib(1)=1, fib(9) equals:
- 21
- 55
- 13
- 34
Show the answer
D. The sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.