Branching recursion
After this: Count the calls in the tree of the Fibonacci function, and remove the repeats with a memo.
On this page · 8 sections · 3 checks
Every recursive function so far has made one smaller call, so the calls have formed a straight chain. This lesson looks at a function that calls itself twice. Its calls spread out like the branches of a tree, and their number grows very fast. Then we fix that with a small note-keeping habit.
The Fibonacci numbers
The Fibonacci numbers are a famous list of numbers. The first two are 0 and 1. Every later number is the sum of the two before it.
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| fib(n) | 0 | 1 | 1 | 2 | 3 | 5 | 8 |
For example, fib(4) is fib(3) + fib(2), which is 2 + 1 = 3. That rule turns directly into a function.
def fib(n): if n < 2: # base cases: fib(0) is 0 and fib(1) is 1 return n return fib(n - 1) + fib(n - 2) # recursive case: two smaller calls
print(fib(4))3
static int fib(int n) { if (n < 2) return n; // base cases: fib(0) is 0 and fib(1) is 1 return fib(n - 1) + fib(n - 2); // recursive case: two smaller calls}
System.out.println(fib(4));3
There are two base cases, 0 and 1. The answer for each one is n itself, so one line covers both. The recursive case makes two smaller calls and adds their answers.
Drawing the calls
fib(4) calls fib(3) and fib(2). Then fib(3) calls fib(2) and fib(1), and so on down to the base cases. If we draw every call, with the calls it makes below it, we get a . Here is the call tree of fib(4). Each line is one call.
fib(4)├── fib(3)│ ├── fib(2)│ │ ├── fib(1)│ │ └── fib(0)│ └── fib(1)└── fib(2) ├── fib(1) └── fib(0)Count the lines and you get 9 calls. Now count how often each call appears.
| Call | Times it runs |
|---|---|
| fib(4) | 1 |
| fib(3) | 1 |
| fib(2) | 2 |
| fib(1) | 3 |
| fib(0) | 2 |
| Total | 9 |
Look at the two copies of fib(2) in the tree. They do the same work and get the same answer. The program does not know this, so it works out fib(2) twice, from nothing.
How fast the calls grow
We can make the program count its own calls.
calls = 0
def fib(n): global calls calls += 1 if n < 2: # base cases: fib(0) is 0 and fib(1) is 1 return n return fib(n - 1) + fib(n - 2) # two smaller calls
print(fib(4), calls)calls = 0print(fib(20), calls)3 9 6765 21891
static int calls = 0;
static int fib(int n) { calls++; if (n < 2) return n; // base cases: fib(0) is 0 and fib(1) is 1 return fib(n - 1) + fib(n - 2); // two smaller calls}
System.out.println(fib(4) + " " + calls);calls = 0;System.out.println(fib(20) + " " + calls);3 9 6765 21891
Here is what the new lines do.
callsis a counter that sits outside the function, so all the calls share it.- Each run of
fibadds one to the counter as it starts. In Python, the lineglobal callsis what lets the function change a variable outside it. - The last lines print the answer and the count, first for
fib(4)and then, after setting the counter back to 0, forfib(20).
You can also work out the count by hand from the tree. The tree of fib(4) holds the first call, the whole tree of fib(3) (5 calls), and the whole tree of fib(2) (3 calls). That is 1 + 5 + 3 = 9. The same rule works for any n of 2 or more: calls(n) = calls(n − 1) + calls(n − 2) + 1.
| n | fib(n) | Calls |
|---|---|---|
| 3 | 2 | 5 |
| 4 | 3 | 9 |
| 5 | 5 | 15 |
| 6 | 8 | 25 |
| 20 | 6,765 | 21,891 |
Each time n goes up by one, the number of calls is multiplied by about 1.6. Growth like this, where each step multiplies the total, is called . It gets large very quickly: fib(20) makes 21,891 calls to produce 6,765.
Wide, not deep
The tree has many calls, but the stack stays short. A frame is popped before the next branch starts, so only one path through the tree is on the stack at any moment. For fib(4), the longest path is fib(4), fib(3), fib(2), fib(1). So the stack never holds more than 4 frames, even though there are 9 calls. For any n of 1 or more, the stack never holds more than n frames.
So these are two different measures.
- Depth is the number of frames on the stack at the deepest moment. It is the longest path from the top of the tree.
- Total work is the number of calls. It is every line in the tree.
Watch it happen
- fib(3)Call fib(3) and watch the call tree. It makes five calls, and fib(1) runs twice.
- fib(4)
- empty
- no calls yet
Call a function to push its first frame.
- calls
- 0
- depth
- 0
Watch the call tree on the right fill in as calls return. The left branch always finishes before the right branch starts, because the left call is made first and the frame waits for it.
A memo removes the repeats
Suppose a friend asks you what 17 × 23 is. You work it out, get 391, and write it on a note. If your friend asks again, you read the note and do no work.
The same idea fixes fib. The first time a call works out an answer, it stores the answer. If the same call is made again, it looks the answer up. A stored answer of this kind is called a , which is short for a written note, and using memos this way is called memoization.
To store the memos we use a hash map, which is a dict in Python and a HashMap in Java. A hash map stores each value under a key and finds it again in about one step. Here the key is n and the value is the answer for n. The hash maps tutorial shows this same pattern in Hash maps in practice. The code calls the map cache, a common name for a store of saved answers.
cache = {}calls = 0
def fib(n): global calls calls += 1 if n < 2: return n if n in cache: # already worked out: look it up return cache[n] cache[n] = fib(n - 1) + fib(n - 2) # worked out once, then stored return cache[n]
print(fib(20), calls)6765 39
static Map<Integer, Integer> cache = new HashMap<>();static int calls = 0;
static int fib(int n) { calls++; if (n < 2) return n; if (cache.containsKey(n)) return cache.get(n); // already worked out: look it up int result = fib(n - 1) + fib(n - 2); cache.put(n, result); // worked out once, then stored return result;}
System.out.println(fib(20) + " " + calls);6765 39
The function has one new check and one new store. Before it works anything out, it looks in cache. If the answer is there, it returns the answer at once. If not, it works out the answer, stores it, and then returns it. The counter is still here, so we can compare the number of calls.
Here is fib(4) with a memo.
fib(4)callsfib(3), which callsfib(2), which callsfib(1)andfib(0). That is 5 calls so far.fib(2)works out 1 + 0 = 1 and stores it.fib(3)callsfib(1), which is call 6. It works out 1 + 1 = 2 and stores it.fib(4)callsfib(2), which is call 7. This answer is stored, so it returns 1 at once. It does not callfib(1)orfib(0)again.fib(4)works out 2 + 1 = 3 and stores it.
That is 7 calls and not 9. The gap gets much bigger as n grows: fib(20) now makes 39 calls in place of 21,891. Each answer from fib(2) to fib(20) is worked out once, and every repeat is a quick lookup. The work is now O(n), which means it grows at the same rate as n. Counting steps explains this notation.
Check yourself
In the call tree of fib(4), which calls run more than once?
fib(4) made 9 calls. What does this print for fib(5)?
calls = 0
def fib(n): global calls calls += 1 if n < 2: return n return fib(n - 1) + fib(n - 2)
print(fib(5), calls)static int calls = 0;
static int fib(int n) { calls++; if (n < 2) return n; return fib(n - 1) + fib(n - 2);}
System.out.println(fib(5) + " " + calls);Use the memo code from this lesson. Its counter counts every call, including calls answered from the memo. How many calls does fib(5) make?
Connect
- Draw the call tree of the Fibonacci function and count its calls: fib(4) makes 9.
- Point to the repeated work: fib(2) runs twice and fib(1) runs three times.
- Tell depth from total work: fib(4) makes 9 calls but never has more than 4 frames on the stack.
- Remove the repeats with a memo: store each answer under its argument, so that each one is worked out once.