Sub topic 15
Mutual Recursion
So far, every recursive function in this tutorial has called itself. Mutual recursion is a pattern where two or more functions call each other in a cycle: f calls g, and g calls f. No function calls itself directly, but the group as a whole is recursive.
This chapter assumes you already know base cases, recursive cases, how the call stack holds one frame per active call, the recursive leap of faith, and how Python raises RecursionError when the stack gets too deep. Everything from those chapters still applies. The only new idea is that the base cases and the progress toward them are spread across several functions.
A First Example: Even and Odd
The smallest example defines "even" and "odd" in terms of each other:
- 0 is even.
- 0 is not odd.
- A positive number
nis even ifn - 1is odd. - A positive number
nis odd ifn - 1is even.
Each rule turns 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, and each recursive call passes n - 1. The two functions share one progress measure, the value of n. Every call in the chain reduces it by one, no matter which function makes the call.
Nobody computes parity this way in practice, because n % 2 == 0 does it in one step. The example is useful because it shows the structure with nothing else in the way.
How the Call Stack Handles It
The call stack does not care which function a frame belongs to. When is_even(3) calls is_odd(2), Python pushes a new frame for is_odd on top of the frame for is_even, exactly as it would for a self-call. The frames alternate between the two functions until one of them reaches a base case. Then the return value passes back down through every frame unchanged.
The stack depth is n + 1 frames, the same as a self-recursive countdown. Mutual recursion has no special cost and no special protection. Python's recursion limit counts every frame, so is_even(5000) raises RecursionError under the default limit of 1000.
Reasoning About Termination
With one function, you check that each recursive call moves toward a base case. With mutual recursion you check the whole cycle. Pick a measure, such as a number, a list length, or a position in the input, and confirm two things:
- Every call from any function in the group to any other function in the group either decreases the measure or keeps it the same, and going once around any cycle strictly decreases it.
- When the measure reaches its minimum, whichever function is called has a base case for it.
For is_even and is_odd, the measure is n. Every call decreases it, and both functions handle n == 0. That proof covers non-negative integers only.
The leap of faith works across function boundaries as well. When you write is_even, assume is_odd is correct for smaller inputs, and the reverse. If each function is correct given that assumption, and the measure strictly decreases, the group is correct.
A Realistic Example: Parsing Arithmetic
Mutual recursion shows up naturally when the data is described by rules that refer to each other. Arithmetic expressions are a classic case. A grammar for them looks like this:
- An expression is one or more terms joined by
+or-. - A term is one or more factors joined by
*or/. - A factor is a number, a minus sign followed by a factor, or an expression in parentheses.
The definition of a factor refers back to expressions, so the rules form a cycle. A recursive descent parser writes one function per rule and lets the functions call each other:
import re
def tokenize(text):
return re.findall(r"\d+|[-+*/()]", text)
def parse(text):
tokens = tokenize(text)
pos = 0
def peek():
return tokens[pos] if pos < len(tokens) else None
def advance():
nonlocal pos
tok = tokens[pos]
pos += 1
return tok
def expr():
value = term()
while peek() in ("+", "-"):
op = advance()
right = term()
value = value + right if op == "+" else value - right
return value
def term():
value = factor()
while peek() in ("*", "/"):
op = advance()
right = factor()
value = value * right if op == "*" else value / right
return value
def factor():
tok = peek()
if tok is None:
raise SyntaxError("unexpected end of input")
if tok == "(":
advance()
value = expr()
if peek() != ")":
raise SyntaxError("expected ')'")
advance()
return value
if tok == "-":
advance()
return -factor()
if tok.isdigit():
advance()
return int(tok)
raise SyntaxError(f"unexpected token {tok!r}")
result = expr()
if peek() is not None:
raise SyntaxError(f"unexpected token {peek()!r}")
return result
print(parse("2 * (3 + 4)")) # 14
print(parse("-(1 + 2) * 3")) # -9
print(parse("10 - 4 - 3")) # 3The cycle is expr → term → factor → expr. Here the progress measure is pos, the number of tokens consumed. factor calls expr only after it consumes a (, and it calls itself only after it consumes a -. So every trip around a cycle consumes at least one token, and the input is finite, which means the recursion must end. The base case is the number branch in factor, which returns without making any further call.
Notice also what is not recursive. Repeated + and * operators are handled with while loops, not recursion. This keeps 10 - 4 - 3 left-associative, so it evaluates as (10 - 4) - 3 = 3, and it keeps the stack shallow for long flat expressions. Recursion is used only for nesting, which is the part of the problem that is actually recursive.
Every nesting level adds three frames (expr, term, factor). An input with about 330 nested parentheses therefore exceeds the default recursion limit. Real parsers either accept this limit or set an explicit maximum nesting depth and report a clear error when the input goes past it.
Where Mutual Recursion Appears
| Situation | Functions that call each other | Progress measure |
|---|---|---|
| Parsing nested syntax (JSON, arithmetic, programming languages) | One function per grammar rule | Tokens consumed |
| Walking data where lists contain dicts and dicts contain lists | `walk_list`, `walk_dict` | Remaining nesting depth |
| Two-player game search (minimax) | `max_value`, `min_value` | Moves remaining |
| State machines written as functions | One function per state | Input position |
Collapsing Mutual Recursion into One Function
You can always merge a mutually recursive group into a single function by passing a parameter that says which role the function is playing:
def parity(n, want_even):
if n == 0:
return want_even
return parity(n - 1, not want_even)
print(parity(10, True)) # True (is 10 even?)
print(parity(7, False)) # True (is 7 odd?)This version behaves exactly like the original pair and uses the same stack depth. Merging is worth doing when the functions are small and nearly identical. For the parser it would make the code worse, because each grammar rule has its own logic, and separate functions keep each rule readable. The techniques from the chapters on loops and explicit stacks work on mutually recursive code too. You track which function each pending frame belongs to, just as want_even does here.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| One function in the cycle has no base case for the minimum value | `RecursionError` for some inputs | Check the base cases of every function at the measure's minimum |
| A cycle that does not consume input (for example, `expr` calling `term` calling `expr` with no token read) | Infinite recursion even on tiny inputs | Make sure every cycle strictly decreases the measure |
| Input outside the assumed domain, such as a negative `n` | `RecursionError` instead of a clear error | Validate at the entry point |
| Using recursion for flat repetition | Deep stacks on long but simple input | Use loops for repetition and recursion for nesting |
Exercise
Write mutually recursive functions countlist(items) and countdict(d) that return how many integers appear anywhere in nested data, where lists and dicts can contain integers, lists, or dicts (count only dict values, not keys). What is the progress measure, and what are the base cases?
Show answer
def countvalue(v): return 1 if isinstance(v, int) else countlist(v) if isinstance(v, list) else countdict(v). Then countlist(items) returns sum(countvalue(x) for x in items), and countdict(d) returns sum(count_value(v) for v in d.values()). The progress measure is the remaining nesting depth: each call goes one level into a strictly smaller piece of the structure. The base cases are an integer, which returns 1 with no further call, and an empty list or dict, where sum over nothing returns 0.
Exercise
In the parser, suppose factor handled parentheses by calling expr() before calling advance() to consume the "(". What would happen when parsing "(1)"?
Show answer
factor would see "(" and call expr, which calls term, which calls factor. That factor sees the same "(" because pos has not moved, so it calls expr again. The cycle never consumes a token, the measure never decreases, and Python raises RecursionError.
Exercise
How many stack frames does parse("((2))") use at its deepest point, counting parse itself?
Show answer
parse calls expr, which calls term, which calls factor (3 frames for the outer level). That factor calls expr, term, and factor for the second "(" (3 more), and those call expr, term, and factor for the number 2 (3 more). The deepest point is 1 + 3 + 3 + 3 = 10 frames, plus a short-lived frame for peek or advance at the top.