Sub topic 1
From recursion to repeated work
Recursion is a natural way to solve a problem that is defined in terms of smaller versions of itself. The recursive code is usually short and easy to check against the definition. It can also do a large amount of hidden repeated work. This chapter shows where that repeated work comes from, because dynamic programming is the technique for removing it.
Prerequisites
This chapter assumes you can already do the following:
- Write Python functions and loops.
- Explain how a recursive function reaches its base case.
- Use lists and dictionaries, including
collections.Counter. - Read Big-O notation such as O(n) and O(2^n).
Recursive decomposition
A recursive solution has two parts:
- Base cases: inputs small enough to answer directly.
- A recursive step: an answer for a larger input built from answers to smaller inputs.
The Fibonacci numbers follow this shape. fib(0) = 0, fib(1) = 1, and every later value is the sum of the two before it. The code is a direct translation:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)This function is correct. fib(10) returns 55 immediately. fib(35) takes several seconds, and fib(50) will not finish in any reasonable time. The definition did not get harder, so the slowdown must come from how the function runs.
Drawing the call tree
Each call to fib makes up to two more calls. If you draw every call as a node, you get a call tree. Here is the tree for fib(4):
fib(2) is computed twice, and fib(1) is computed three times. Each repeated call does the whole computation again because the function keeps no record of earlier answers. In larger trees, whole subtrees repeat, and the repeats have repeats of their own.
Measuring the repeated work
You can count the repetition directly by recording how many times each argument is seen:
from collections import Counter
calls = Counter()
def fib(n):
calls[n] += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10))
for n in sorted(calls):
print(n, calls[n])
print("total calls:", sum(calls.values()))The output shows 55, then these counts:
| Argument | Times called |
|---|---|
| 10 | 1 |
| 8 | 2 |
| 6 | 5 |
| 4 | 13 |
| 2 | 34 |
| 1 | 55 |
| 0 | 34 |
The script prints all eleven arguments, but the table lists only every other one. The total is 177 calls, and there are only 11 distinct arguments (0 through 10). The counts are Fibonacci numbers themselves, which means the work grows about as fast as the answer does, roughly by a factor of 1.618 for each step up in n. Computing fib(30) takes 2,692,537 calls to answer a question that has only 31 distinct sub-questions.
Common mistakes
- Blaming recursion itself. Function-call overhead is not the issue. The problem is calling the function with the same argument many times.
- Assuming the depth predicts the cost. A tree that is only
nlevels deep can still contain an exponential number of nodes. - Testing only small inputs.
fib(20)feels instant, so the exponential growth goes unnoticed until the input grows a little.
The same pattern appears in many problems besides Fibonacci, where a short recursive definition hides a large amount of repeated work. The following chapters show how to recognize this pattern and how to compute each distinct subproblem only once.
Exercise
When naive fib(6) runs, how many times is fib(2) called, and how many calls are made in total?
Show answer
fib(2) is called 5 times, which is fib(5). The total is 2 fib(7) - 1 = 2 13 - 1 = 25 calls.
Exercise
The naive fib(n) recursion has a depth of only about n. Why does it still take exponential time?
Show answer
Each call branches into two calls, so the number of nodes in the call tree grows exponentially even though each path from root to leaf has only about n nodes. Most of those nodes repeat arguments that were already computed elsewhere in the tree.