Sub topic 14
Mutual Recursion
This chapter assumes you have read the earlier chapters on the call stack, depth limits, and turning tail recursion into a loop. You should be comfortable reading Python functions, tracing stack frames, and recognizing a tail call.
Most recursion in this tutorial has been direct, meaning a function calls itself. Mutual recursion is indirect. Function A calls function B, and B calls A again, either directly or through other functions. The cycle can include two functions or many. The usual rules still apply. There must be a base case that ends the cycle, each call must move toward that base case, and every call adds a frame to the same call stack.
A Minimal Example: Even and Odd
The classic example defines evenness in terms of oddness, and oddness in terms of evenness.
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. Each recursive case hands a smaller problem to the other function. Neither function makes sense alone, but together they form a complete definition.
n % 2 == 0 would do this job in constant time, so nobody should check parity this way in real code. The example is useful because the structure is easy to see.
What the Call Stack Looks Like
Mutual recursion does not get a separate stack for each function. Frames from both functions are interleaved on one stack. Here is the trace of is_even(3):
At the deepest point the stack holds four frames, one for each value from 3 down to 0. Stack depth therefore grows linearly with n, just as in direct recursion. CPython's recursion limit counts all frames, whichever function they belong to:
import sys
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(sys.getrecursionlimit()) # typically 1000
try:
is_even(100_000)
except RecursionError as e:
print("RecursionError:", e)Common Errors
Mutual recursion makes some mistakes harder to spot. In direct recursion the base case and the recursive call sit in the same function. Here they are spread across several.
| Error | What happens | Fix |
|---|---|---|
| A function in the cycle has no base case and the others never reach theirs | Infinite recursion ends in `RecursionError` | Check every path around the cycle for a reachable base case |
| Input outside the domain, such as `is_even(-1)` | `n` moves away from 0 forever | Validate input at the entry point, for example `if n < 0: raise ValueError` |
| A path through the cycle that does not shrink the problem | Calls loop without making progress | Make sure at least one step in every cycle reduces the input |
| Base cases that disagree | Wrong answers, for example both functions returning `True` at 0 | Write down what each function means and check the base cases against those meanings |
Where Mutual Recursion Appears Naturally
The even/odd pair is a toy. Mutual recursion becomes the clearest design when the problem itself has mutually defined parts. The main cases are these:
- Grammars and parsers. An expression contains terms, a term contains factors, and a factor can contain a parenthesized expression.
- Nested data formats. A JSON value can be an array or an object, and arrays and objects contain values.
- State machines. Each state can be a function that hands control to the next state.
- Game trees. A "max player" function calls a "min player" function and the other way round.
A recursive descent parser is the standard real-world example. The grammar below handles +, *, integers, and parentheses:
import re
def tokenize(text):
return re.findall(r"\d+|[()+*]", text)
def parse_expr(tokens, i):
value, i = parse_term(tokens, i)
while i < len(tokens) and tokens[i] == "+":
rhs, i = parse_term(tokens, i + 1)
value += rhs
return value, i
def parse_term(tokens, i):
value, i = parse_factor(tokens, i)
while i < len(tokens) and tokens[i] == "*":
rhs, i = parse_factor(tokens, i + 1)
value *= rhs
return value, i
def parse_factor(tokens, i):
if i >= len(tokens):
raise SyntaxError("unexpected end of input")
tok = tokens[i]
if tok == "(":
value, i = parse_expr(tokens, i + 1)
if i >= len(tokens) or tokens[i] != ")":
raise SyntaxError("expected ')'")
return value, i + 1
if tok.isdigit():
return int(tok), i + 1
raise SyntaxError(f"unexpected token {tok!r}")
def evaluate(text):
tokens = tokenize(text)
value, i = parse_expr(tokens, 0)
if i != len(tokens):
raise SyntaxError("trailing tokens")
return value
print(evaluate("1+2*3")) # 7
print(evaluate("2*(3+4)")) # 14
print(evaluate("((5))*2")) # 10The parser uses both techniques, each for a different job. A while loop handles 1+2+3+4 because those terms sit at the same level, so no extra stack depth is needed. Mutual recursion handles parentheses because nesting really is recursive. This split is a good general rule: use iteration for repetition across a sequence and recursion for depth.
The parser's stack depth follows the nesting depth of the input, not its length. Each level of parentheses costs three frames (parse_expr, parse_term, parse_factor). With CPython's default limit of 1000, input nested about 330 levels deep raises RecursionError. If the parser accepts untrusted input, this is a denial-of-service risk. Production parsers often set an explicit maximum nesting depth and raise a clear error when input goes past it.
Tail Calls Across Functions
In is_even and is_odd, every recursive call is a tail call, because it is the last thing the function does. Languages with full tail-call optimization reuse the frame for tail calls to any function, not only to the function itself. Scheme requires this behavior, which is why mutually recursive state machines are idiomatic there.
Many languages only optimize self-recursion, or do not optimize tail calls at all:
- Scala.
@tailreconly accepts self-recursive calls. The standard library providesscala.util.control.TailCallsfor mutual cases. - Clojure.
recuronly targets the current function. Mutual tail calls go through the built-intrampolinefunction. - Python. CPython performs no tail-call optimization of any kind.
In these languages you need one of the conversions below.
Converting Mutual Recursion to Iteration
Merging into one loop with a state variable
When every call in the cycle is a tail call, you can merge the functions into one loop. Each function becomes a value of a state variable. Each tail call becomes an update to the state and the parameters, which is the same move the earlier chapter used for self tail recursion.
def is_even_loop(n):
if n < 0:
raise ValueError("n must be non-negative")
state = "even"
while n != 0:
state = "odd" if state == "even" else "even"
n -= 1
return state == "even"
print(is_even_loop(100_000)) # True
print(is_even_loop(7)) # FalseTrampolining
A trampoline keeps the functions separate. Instead of making a tail call, a function returns a thunk, which is a zero-argument function that will make the call later. A driver loop keeps calling thunks until it gets a non-callable value.
def is_even_t(n):
if n == 0:
return True
return lambda: is_odd_t(n - 1)
def is_odd_t(n):
if n == 0:
return False
return lambda: is_even_t(n - 1)
def trampoline(result):
while callable(result):
result = result()
return result
print(trampoline(is_even_t(100_000))) # TrueStack depth stays constant because each function returns before the next one runs. The costs are a heap allocation for each step and one gotcha: if the real result can be a function, the driver cannot tell it apart from a thunk. In that case, wrap thunks in a dedicated class and check for that class with isinstance.
Non-tail cycles
The parser's calls are not tail calls. After parse_factor calls parse_expr, it still has to check for ). Those cycles need the explicit-stack technique from the earlier chapter, with each stack entry recording which function to resume and where. That works, but the code gets much harder to read. For parsers, the usual choice is to keep the recursion and enforce a depth limit.
| Technique | Works for | Stack depth | Readability |
|---|---|---|---|
| Plain mutual recursion | Any cycle | O(depth) | Highest |
| Merged loop with state variable | All tail calls | O(1) | Good for small cycles |
| Trampoline | All tail calls | O(1) | Keeps functions separate |
| Explicit stack | Any cycle | O(depth) on the heap | Lowest |
Exercise
Write mutually recursive functions counta(s) and countb(s), where s is a string of 'a' and 'b' characters. counta should return True if the string, read from the current position, is in "expect a" state at the end, and the functions alternate: counta consumes an 'a' and hands off to countb, and countb consumes a 'b' and hands off to counta. Both return True on an empty string when in counta's turn and False in countb's turn, and False on any unexpected character. Which inputs make counta return True?
Show answer
def counta(s): return True if s == "" else (s[0] == "a" and countb(s[1:])); def countb(s): return False if s == "" else (s[0] == "b" and counta(s[1:])). count_a returns True exactly for "", "ab", "abab", and so on: strings made of zero or more repetitions of "ab". Every hand-off is a tail call, so the pair can be merged into one loop with a state variable.
Exercise
Each level of parentheses in the evaluate parser uses three stack frames. Under CPython's default limit of 1000, roughly how deep can the nesting go, and why does a long flat input like "1+1+1+...+1" with 10,000 terms not raise RecursionError?
Show answer
About 330 levels, because 1000 / 3 ≈ 333 minus a few frames for evaluate and the module. A flat sum does not recurse deeper with each term. The while loop in parse_expr consumes each "+" at the same level, so stack depth stays constant no matter how many terms there are.
Exercise
Why does the trampoline fail if a mutually recursive function's real return value is a function object, and how would you fix it?
Show answer
The driver treats every callable as a thunk, so it would call the real result instead of returning it. Fix this by wrapping deferred calls in a dedicated class, such as class Bounce holding a function and arguments, and loop only while isinstance(result, Bounce).