Sub topic 3
The Recursive Case: Making the Problem Smaller
This chapter assumes you can read Python functions and conditionals, and that you know what a base case is from the previous chapter. Here we look at the other half of every recursive function. The recursive case is the branch that calls the function again on a smaller input.
The Two Jobs of the Recursive Case
A recursive case has two jobs:
- Reduce: call the function on an input that is closer to the base case.
- Combine: use the result of that call to build the answer for the current input.
Factorial shows both jobs on one line:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120The call factorial(n - 1) reduces the problem. Multiplying the result by n combines it into the answer.
Measuring Progress
"Smaller" needs a precise meaning. Choose a measure of size that is a non-negative whole number, such as n itself, the length of a list, or the number of characters in a string. A recursive function terminates when two things hold:
- Every recursive call gets an input with a strictly smaller measure.
- Every chain of shrinking inputs eventually reaches a base case.
If you can name the measure and show that it shrinks on every call, you have shown the function stops.
Common Errors
| Bug | Example recursive call | What happens |
|---|---|---|
| No progress | `factorial(n)` | The same input is passed forever |
| Wrong direction | `factorial(n + 1)` | The input moves away from 0 |
| Skipping the base case | `f(n - 2)` with base case `n == 0` | Odd inputs pass 1, then -1, and never hit 0 |
| Unhandled inputs | `factorial(-3)` | A negative start never reaches 0 |
In CPython, each of these bugs usually ends in a RecursionError instead of an answer. A later chapter covers that limit.
The skipping bug is easy to miss. You can fix it in two ways: widen the base case, or reject bad inputs before you recurse.
def sum_every_other(n):
"""Sum n, n-2, n-4, ... down to 1 or 0."""
if n < 0:
raise ValueError("n must be non-negative")
if n <= 1: # covers both 0 and 1
return n
return n + sum_every_other(n - 2)
print(sum_every_other(6)) # 6 + 4 + 2 + 0 = 12
print(sum_every_other(5)) # 5 + 3 + 1 = 9Checklist for a Recursive Case
- Name the size measure.
- Confirm that each call strictly reduces it.
- Confirm that every input either is a base case or can reach one.
- Check that the combine step turns the smaller answer into the correct full answer.
Exercise
The function def power(b, e): return 1 if e == 0 else b * power(b, e - 1) works for e = 3. What is its size measure, and which inputs make it fail to terminate?
Show answer
The size measure is the exponent e, which shrinks by 1 on each call. A negative e such as -1 moves away from the base case e == 0, so the function never terminates. You can fix it by rejecting negative exponents or by handling them separately.
Exercise
Write a recursive function digits(n) that returns the number of decimal digits in a non-negative integer n. State its size measure.
Show answer
def digits(n): return 1 if n < 10 else 1 + digits(n // 10). Dividing by 10 removes one digit, so the size measure is the number of digits, and it shrinks by 1 on each call until n < 10.