Sub topic 14
Mutual Recursion
This chapter assumes you already know how a recursive function uses a base case and a recursive case, and how each call pushes a frame onto the call stack. It also assumes you have seen tail recursion turned into a loop earlier in the tutorial.
What Mutual Recursion Is
In direct recursion, a function calls itself. In mutual recursion, two or more functions call each other in a cycle. Function A calls B, and B calls A. The functions still need base cases, but you have to read them as a group to see that every path ends.
The classic example decides whether a non-negative integer is even or odd:
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)) # TrueThe logic follows from one fact: n is even exactly when n - 1 is odd. Each function has its own base case at n == 0, and each recursive call moves n one step closer to zero.
Frames Still Pile Up
Calling a different function does not avoid the call stack. Every call to is_even or is_odd adds a frame to the same stack, and the frames alternate between the two functions.
The stack depth is n + 1, so mutual recursion runs into the same depth limit as direct recursion:
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)
try:
is_even(100_000)
except RecursionError as e:
print("RecursionError:", e)Turning Mutual Tail Calls into a Loop
Both recursive calls above are tail calls, because the result is returned directly with no further work. That lets you remove the recursion. Replace "which function am I in" with a variable and loop. Here a boolean tracks whether we are currently answering "is even?" or "is odd?":
def is_even_loop(n):
even = True # True means we are in is_even, False means is_odd
while n != 0:
even = not even # switch to the other function
n -= 1
return even # is_even(0) is True, is_odd(0) is False
print(is_even_loop(10)) # True
print(is_even_loop(7)) # False
print(is_even_loop(100_000)) # TrueThis is the same accumulator-to-loop conversion used for single-function tail recursion. The only new piece is the state variable. With three or more functions, that variable becomes a small enum or string naming the current function.
Where You Meet It in Practice
Toy parity checks are rare in real code, but mutual recursion shows up naturally when the data or grammar it walks is itself mutually defined:
| Domain | Mutually recursive pieces |
|---|---|
| Recursive descent parsers | `parse_expression` calls `parse_term`, which calls `parse_factor`, which calls `parse_expression` for parentheses |
| JSON or nested config walkers | A `visit_object` function calls `visit_value`, which may call `visit_object` or `visit_list` |
| State machines | Each state is a function that calls the next state's function |
In parsers, the calls are usually not tail calls, and the nesting depth is limited by the input. Recursion is usually fine there. If untrusted input could nest thousands of levels deep, put an explicit depth check in place or switch to an explicit stack.
Exercise
How many stack frames for iseven and isodd are active at the deepest point of the call is_even(10), and which function call actually returns the final answer at the base case?
Show answer
There are 11 frames: iseven(10), isodd(9), iseven(8), and so on down to n = 0. Because the functions alternate and 10 is even, the base case is reached in iseven(0), which returns True. That value is passed back unchanged through all the other frames.
Exercise
Write isoddloop(n) using the same state-variable technique, so that it gives the same results as is_odd for non-negative n.
Show answer
Start in the "odd" state and flip on each step: def isoddloop(n): odd = True; while n != 0: odd = not odd; n -= 1; return not odd. The state starts as "we are in isodd". If we end in isodd, isodd(0) returns False, which is why the function returns not odd. A simpler equivalent is return not iseven_loop(n).