Mutual Recursion for Even/Odd Check in Python
Implements even and odd checks using two functions that call each other recursively, demonstrating base cases and alternating calls.
Python code
13 linesdef 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)
if __name__ == "__main__":
for num in range(0, 11):
print(f"{num}: even={is_even(num)}, odd={is_odd(num)}")
Output
0: even=True, odd=False
1: even=False, odd=True
2: even=True, odd=False
3: even=False, odd=True
4: even=True, odd=False
5: even=False, odd=True
6: even=True, odd=False
7: even=False, odd=True
8: even=True, odd=False
9: even=False, odd=True
10: even=True, odd=False
How it works
Mutual recursion works because each function reduces n by 1 and delegates to the other, so the two functions alternate calls as n decreases. The base cases stop the chain at n == 0, where is_even returns True and is_odd returns False, matching the mathematical definition. This pattern is a clear illustration of how recursion can be split across multiple functions. Note that for large n, this will hit Python's recursion limit (default 1000), so it is best used for educational purposes or small inputs.
Common mistakes
- Swapping the base-case return values (True for is_odd or False for is_even)
- Forgetting to decrement n, causing infinite recursion
- Using modulo (%) as a shortcut instead of exploring the recursive design
Variations
- Use a single is_even function with `not is_even(n - 1)` instead of a separate is_odd
- Switch to iterative loop with two booleans for O(1) space and faster performance
Real-world use cases
- Teaching recursion and algorithm design in computer science courses.
- Demonstrating indirect recursion in language interpreter design where parses alternate rules.
- Modeling turn-based state transitions where each state delegates to the next state.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.