Sub topic 15
Mutual Recursion
This chapter assumes you know what base cases and recursive cases are, and that you can trace calls on the call stack. Earlier chapters covered both.
What Mutual Recursion Is
So far, every recursive function has called itself. Mutual recursion is when two or more functions call each other in a cycle: f calls g, and g calls f. No single function calls itself directly. The recursion still happens, because the chain of calls loops back.
The rules from earlier chapters still apply, but now they cover the whole group of functions:
- The cycle needs at least one base case that stops it.
- Every step around the cycle must move the input closer to that base case.
A Worked Example: Even and Odd
A number is even if the number one below it is odd. A number is odd if the number one below it is even. Zero is even and not odd. Those three facts translate directly into code:
def is_even(n):
if n == 0:
return True
return is_odd(n - 1)
def is_odd(n):
if n == 0:
return False
return is_even(n - 1)
print(is_even(10)) # True
print(is_odd(7)) # TrueEach function has its own base case at n == 0, and each call passes n - 1, so every call moves toward zero. The two functions share the work. Neither one could do the job alone.
Tracing the Calls
The call stack works exactly as it does for ordinary recursion. Each call pushes a frame, and the frames alternate between the two functions.
The answer comes from whichever base case the chain reaches. An odd starting number reaches zero inside the other function, so the result flips.
Where Mutual Recursion Shows Up
The even/odd pair is a teaching example. In practice, mutual recursion shows up when a problem's structure has several kinds of parts that contain each other:
| Situation | Functions that call each other |
|---|---|
| Expression parsers | `parse_expression` calls `parse_term`, which calls `parse_expression` for parenthesized input |
| Nested data such as JSON | `walk_dict` calls `walk_list` and `walk_list` calls `walk_dict` |
| State machines | One function per state, each calling the function for the next state |
Common Errors
- A missing or unreachable base case. If any path around the cycle skips every base case, the calls never stop. For example,
is_even(-1)counts down past zero forever. - No progress on some step. If one function passes its input along unchanged, the cycle can spin without shrinking the input.
- Hidden depth. Each step around the cycle adds a frame.
is_even(5000)uses about 5000 frames and raisesRecursionErrorin CPython's default configuration.
Exercise
What happens when you call is_even(-1), and how would you fix it?
Show answer
The calls go isodd(-2), iseven(-3), and so on. n never equals 0, so the recursion continues until Python raises RecursionError. To fix it, check for a negative input at the start (for example, raise ValueError when n < 0), or call is_even(abs(n)), because a negative number has the same parity as its absolute value.
Exercise
How many stack frames does is_odd(4) create, counting the first call, and what does it return?
Show answer
The calls are isodd(4), iseven(3), isodd(2), iseven(1), and isodd(0), which makes five frames. The last call reaches the base case of isodd and returns False, so is_odd(4) returns False.