Sub topic 4
Tracing a Recursive Call Step by Step
This chapter assumes you can write Python functions and that you know a recursive function has a base case and a recursive case. It also assumes you know that each call gets its own stack frame on the call stack. Here you will practice following a recursive call by hand and with print statements, so you can predict its output and find bugs.
The Two Phases of a Trace
Every recursive trace has two phases:
- Winding. Calls go deeper. Each call does its work up to the recursive call, then pauses and waits.
- Unwinding. The base case returns a value. Each paused call resumes, finishes its pending work, and returns to its caller.
The most common tracing error is to treat a call as finished when it reaches the recursive call. It is not finished yet. The multiplication in n * factorial(n - 1) happens during unwinding, after the inner call returns.
Instrumenting a Function
A depth parameter lets you indent each line of output, so the shape of the call stack shows up in the printed text.
def factorial(n, depth=0):
indent = " " * depth
print(f"{indent}call factorial({n})")
if n == 0:
print(f"{indent}base case -> 1")
return 1
result = n * factorial(n - 1, depth + 1)
print(f"{indent}return {n} * ... = {result}")
return result
factorial(3)Output:
call factorial(3)
call factorial(2)
call factorial(1)
call factorial(0)
base case -> 1
return 1 * ... = 1
return 2 * ... = 2
return 3 * ... = 6Lines sharing an indent belong to the same frame. The "call" lines are the winding phase. The "return" lines are the unwinding phase, and they come out in reverse order.
A Frame Table
When you trace on paper, keep one row per frame. Record what the frame is waiting for and fill in its return value once the value is known.
| Frame | n | Pending work | Returns |
|---|---|---|---|
| 1 | 3 | 3 * (result of frame 2) | 6 |
| 2 | 2 | 2 * (result of frame 3) | 2 |
| 3 | 1 | 1 * (result of frame 4) | 1 |
| 4 | 0 | none (base case) | 1 |
Fill the "Returns" column from the bottom up, because that is the order in which the values become known.
Common Tracing Mistakes
- Sharing variables across frames. Each frame has its own
nand its ownresult. Settingresultin frame 3 does not changeresultin frame 2. - Missing work after the call. Code below the recursive call runs during unwinding, in reverse order. A
printplaced after the call prints the values deepest-first. - Skipping the base case check. Confirm that the argument actually reaches the base case. For example,
factorial(-1)never reachesn == 0and keeps winding until Python raises an error. - Tracing too large an input. Use the smallest input that exercises the recursive case, usually 2 or 3. One level above the base case shows the pattern.
Exercise
Given this function, what does printdownup(2) print, and in what order? def printdownup(n): if n == 0: return print("down", n) printdownup(n - 1) print("up", n)
Show answer
It prints "down 2", "down 1", "up 1", "up 2". The "down" lines run during winding, before each recursive call. The "up" lines run during unwinding, after each inner call returns, so they appear in reverse order.
Exercise
Build a frame table for factorial(2). How many frames exist at the deepest point, and what does each one return?
Show answer
Three frames exist at once: n=2, n=1, and n=0. The n=0 frame returns 1 (base case), the n=1 frame returns 1 1 = 1, and the n=2 frame returns 2 1 = 2.