Before you run it, say out loud what it will print. Then open the answer.
What it prints
5000
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
Each recursive call waits for the one below it, so frames stack up. The peak depth is the most frames open at once and can overflow.
1open a frame
↓
2wait for the call below
↓
3base returns
↓
4frames unwind
Line by line
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
def depth(n):sets nothing on screen
if n == 0:sets nothing on screen
return 0sets nothing on screen
return 1 + depth(n - 1)sets nothing on screen
print(depth(3))3
Why this worksFrames are the cost
Recursion uses memory for every open call. The peak depth is the most frames held at once, and that is what can overflow.
Longest path sets depth
When a frame makes two calls, the stack depth follows the longest chain, not the total number of calls.
Examples
Frames stack up
defdepth(n):
if n == 0:
return0return1 + depth(n - 1)
print(depth(3))
Four frames are open at once before the base returns. Each waits for the next.
One waits for the next
deff(n):
if n == 0:
return0returnf(n - 1)
print(f(2))
f(2) cannot finish until f(1) finishes, which waits on f(0). The calls nest like cups.
Unwind on return
defg(n):
if n == 0:
return0returng(n - 1)
print(g(3))
When the base returns, frames close one by one from the inside out. That is the unwind.
Deep call overflows
deff(n):
if n == 0:
return0returnf(n - 1)
print(f(5))
A very large n opens too many frames and the program crashes. The stack has a fixed size.
Tail calls still stack
deft(n):
if n == 0:
return0returnt(n - 1)
print(t(3))
Python does not reuse the tail frame, so even tail recursion stacks up. Some languages do not.
Depth is the peak frames
defd(n):
if n <= 0:
return0return1 + d(n - 1)
print(d(4))
The deepest point equals the starting n. That peak is the most frames open at once.
Two calls per frame
deffib(n):
if n < 2:
return n
returnfib(n - 1) + fib(n - 2)
print(fib(4))
Each frame can wait on two calls. The stack grows along the longest path, not the count.