Tracing
Recursion
Learn to trace recursive function calls, visualize the call stack, and understand how Python resolves each frame to produce a final result.
What Is Recursion?
A function is recursive when it calls itself as part of its own execution. Every recursive function has two essential components: a base case that stops the recursion and a recursive case that moves toward it.
The Call Stack Explained
Python uses a call stack (a last-in, first-out data structure) to keep track of function calls. When a function is called, a new frame is pushed onto the stack. When it returns, the frame is popped off.
Why Tracing Matters
Tracing means manually walking through each call and return to predict the output. It builds a mental model of how Python actually executes your code, which is essential for debugging and designing recursive solutions.
The Two Rules of Recursion
Anatomy of a Recursive Call
Iteration vs Recursion
| Iteration (loop) | Recursion | |
|---|---|---|
| Mechanism | Repeats via for / while | Repeats via self-call |
| State | Updated in variables | Passed as arguments |
| Termination | Loop condition becomes False | Base case is reached |
| Memory | \( O(1) \) (constant) | \( O(n) \) (stack frames) |
| Best for | Simple repetition | Trees, divide & conquer |
How to Trace: Step by Step
Example: Tracing factorial(4)
Example: Tracing sum_list
Example: Fibonacci Tree
Winding vs Unwinding
Head vs Tail Recursion
| Head Recursion | Tail Recursion | |
|---|---|---|
| Work done | After the recursive call returns | Before the recursive call |
| Return expression | n * factorial(n - 1) | factorial(n - 1, acc * n) |
| Stack usage | Must keep all frames | Could reuse one frame |
| Python optimized? | No | No (Python has no TCO) |
Tracing with an Accumulator
Notice: with an accumulator, the result is built up during winding. The unwinding phase just passes the final value back unchanged through every frame.
Common Mistakes
Recursion Cheat Sheet
| Concept | Key Idea |
|---|---|
| Base Case | Returns a value without recursing |
| Recursive Case | Calls itself with a smaller input |
| Call Stack | LIFO structure storing each frame |
| Winding | Calls are pushed, waiting to resolve |
| Unwinding | Return values propagate back up |
| Time Complexity | Depends on branching: linear or exponential |
| Stack Overflow | RecursionError when limit (~1000) exceeded |
Question 1 of 5
def mystery(n):
if n <= 0:
return 0
return n + mystery(n - 2)
What does mystery(7) return?
Question 2 of 5
In a recursive function, what happens if there is no base case?
Question 3 of 5
def power(base, exp):
if exp == 0:
return 1
return base * power(base, exp - 1)
How many total stack frames are created when calling power(2, 5) (including the initial call)?
Question 4 of 5
def concat(n):
if n == 0:
return ""
return concat(n - 1) + str(n)
What is the output of concat(4)?
Question 5 of 5
Which of the following best describes unwinding the call stack?