The recursive contract
A recursive function has two parts:
- Base cases that answer the smallest inputs directly.
- A recursive step that reduces the input to strictly smaller instances and combines their answers.
Reason about it by induction: assume the call on a smaller input returns the right answer, and check that the combination is then correct. Do not trace every call in your head. The two common bugs are a missing base case and a step that does not shrink the input, and both give infinite recursion.
Fast exponentiation shows the pattern, and why halving matters:
def fast_pow(x, n):
if n == 0:
return 1
half = fast_pow(x, n // 2) # one recursive call, half the size
return half * half if n % 2 == 0 else half * half * x
print(fast_pow(3, 13)) # 1594323
The recursion depth is about with at most two multiplications per level, so it uses multiplications instead of . Calling fast_pow(x, n // 2) twice instead of storing half would give and throw the gain away.
Recursion trees and repeated work
The naive Fibonacci recursion makes two calls per level:
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
The number of calls satisfies with , whose solution is . For that is calls to compute , growing like .
Yet there are only 31 distinct subproblems, to . The tree recomputes them exponentially often. When subproblems overlap like this, store each answer the first time it is computed: memoisation. The cost becomes
functools.cache and lru_cache
from functools import lru_cache
@lru_cache(maxsize=None) # functools.cache is the same thing
def fib_memo(n):
return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)
print(fib_memo(90)) # 2880067194370816120
print(fib_memo.cache_info()) # CacheInfo(hits=88, misses=91, maxsize=None, currsize=91)
Each of the 91 values is computed once (91 misses), and the 88 hits are the second calls that are now free. Practical points:
- Arguments become dictionary keys, so they must be hashable: pass a tuple, not a list (a list raises
TypeError: unhashable type: 'list'). maxsize=Nonenever evicts; a boundedmaxsizeevicts the least recently used entries.- The cache lives as long as the function. Call
fib_memo.cache_clear()between unrelated inputs, and avoid decorating methods, where the cache holds references toself.
Worked example
ways to make change
How many ways are there to make 100 cents from coins of 1, 5, 10 and 25 cents, where order does not matter? Give the recursion, its complexity and an iterative version.
Show solutionHide solution
Let ways(i, amount) count the ways using only COINS[i:]. Either use COINS[i] at least once more (stay at i, reduce the amount) or never use it again (move to i + 1). Fixing the order of coin types is what stops 5 + 1 and 1 + 5 being counted twice.
from functools import cache
COINS = (1, 5, 10, 25)
@cache
def ways(i, amount):
if amount == 0:
return 1
if amount < 0 or i == len(COINS):
return 0
return ways(i, amount - COINS[i]) + ways(i + 1, amount)
print(ways(0, 100)) # 242
There are at most states for coin types and amount , each doing work, so the time and memory are ; cache_info() reports 541 misses here. Without the cache the recursion revisits the same (i, amount) pairs many times over.
Bottom-up, process one coin type at a time and let w[a] count the ways to make a with the coins seen so far:
def ways_dp(amount, coins=COINS):
w = [1] + [0] * amount
for c in coins:
for a in range(c, amount + 1):
w[a] += w[a - c]
return w[amount]
print(ways_dp(100)) # 242
Same time, memory and no recursion depth at all.
Python's recursion limit
CPython does not optimise tail calls and caps the stack depth: sys.getrecursionlimit() is 1000 by default, and exceeding it raises RecursionError. Memoisation does not help with depth. On an empty cache fib_memo(5000) still has to descend 5000 frames, and it raises RecursionError.
sys.setrecursionlimit raises the cap but not the underlying C stack, so very deep recursion can crash the interpreter outright. In an interview, mention the limit whenever the depth can grow with (linked structures, deep trees, DP over a long sequence) and offer an iterative version:
- Bottom-up DP: fill the table in dependency order, as
ways_dpdid. For Fibonacci, keep the last two values:a, b = b, a + b. - An explicit stack: push what the call stack would have held. This is how you write deep DFS.
Worked example
flattening nested lists without recursion
Flatten arbitrarily nested lists, e.g. [1, [2, [3, 4]], 5, [[6]]] becomes [1, 2, 3, 4, 5, 6]. The natural recursion fails on a list nested 5000 deep. Write a version that does not.
Show solutionHide solution
The recursive version is direct:
def flatten(xs):
out = []
for x in xs:
if isinstance(x, list):
out.extend(flatten(x))
else:
out.append(x)
return out
Each nesting level costs one frame, so 5000 levels raise RecursionError. What does a suspended call remember? Only where it was in its own list. So keep a stack of iterators: descend by pushing a new iterator, and pop when one is exhausted.
def flatten_iter(xs):
out, stack = [], [iter(xs)]
while stack:
for x in stack[-1]: # resume the innermost list where it left off
if isinstance(x, list):
stack.append(iter(x))
break # descend into x
out.append(x)
else: # loop finished without break: list exhausted
stack.pop()
return out
print(flatten_iter([1, [2, [3, 4]], 5, [[6]]])) # [1, 2, 3, 4, 5, 6]
The output order matches the recursion because the iterator on top of the stack is exactly the innermost active call. Time is and the stack is bounded by heap memory, not the recursion limit, so a list nested 5000 deep around 42 returns [42].
Knowledge check
How many calls in total does the naive recursive fib(5) make (including the top-level call), with base cases n < 2?
Knowledge check
You decorate def best(prices, i) with @functools.cache and call best([3, 1, 4], 0). What happens?
Knowledge check
With memoisation, what is the time complexity of counting the ways to make amount A from k coin types using ways(i, amount)?
Key takeaways
- Write base cases first, make every call shrink the input, and reason by induction.
- Overlapping subproblems make naive recursion exponential; memoise and the cost is states × work per state.
functools.cacheneeds hashable arguments; inspect it withcache_info().- Python has no tail-call optimisation and a default depth limit of 1000; caching does not raise it.
- Convert deep recursion to bottom-up DP or an explicit stack, and say so before the interviewer asks.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).