Sub topic 3
The Recursive Case: Making the Problem Smaller
This chapter assumes you can write and call Python functions, use conditionals, and read short code samples. You should also know from the previous chapter what a base case is. Here the focus is the other half of every recursive function: the recursive case. This is the branch that calls the function again on a smaller problem and turns the answer from that call into the answer for the current one.
What the Recursive Case Has to Do
Each recursive case has three jobs:
- Reduce. Build a smaller input from the current one.
- Recurse. Call the function on that smaller input.
- Combine. Use the returned value to produce this call's result.
Factorial shows all three in one line:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120The reduce step is n - 1, the recurse step is factorial(n - 1), and the combine step is n * .... If any of the three is wrong, the function either never stops or returns the wrong answer.
Progress Toward the Base Case
A recursive function terminates only if every chain of calls eventually reaches a base case. The standard way to argue this is to pick a measure: a non-negative whole number computed from the input that gets strictly smaller with every recursive call. A non-negative integer cannot shrink forever, so the chain has to end. It also has to end at a base case, because the base case must cover every input where the measure cannot shrink any further.
For factorial the measure is n itself. Each call lowers it by 1, and the base case catches it at 0.
The measure is not always the raw argument. Here are some common choices:
| Function | Input | Measure | How it shrinks |
|---|---|---|---|
| `factorial(n)` | integer | `n` | decreases by 1 |
| `sum_digits(n)` | integer | number of digits | drops one digit via `n // 10` |
| `power(b, e)` | integer exponent | `e` | halves via `e // 2` |
| `gcd(a, b)` | two integers | `b` | replaced by `a % b`, which is less than `b` |
| `total(items)` | list | `len(items)` | decreases by 1 via slicing |
Shrinking by different amounts
The reduce step does not have to subtract 1. How fast the measure shrinks sets how many calls the function makes.
def sum_digits(n):
if n < 10:
return n
return n % 10 + sum_digits(n // 10)
def power(base, exp):
if exp == 0:
return 1
half = power(base, exp // 2)
if exp % 2 == 0:
return half * half
return half * half * base
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(sum_digits(9045)) # 18
print(power(2, 10)) # 1024
print(gcd(48, 18)) # 6sum_digits removes one digit per call, so a d-digit number takes d calls. power halves the exponent, so power(2, 10) calls itself with exponents 10, 5, 2, 1, 0, which is five calls instead of eleven. In gcd, the first argument actually grows relative to the second, but the second argument is replaced by a remainder that is always smaller than it. Watch the argument that the base case tests. Other arguments can do anything as long as that one shrinks.
Common Errors in the Recursive Case
No progress
The function calls itself on the same input, or on input that the measure does not count as smaller.
def broken_factorial(n):
if n == 0:
return 1
return n * broken_factorial(n) # input never changes
try:
broken_factorial(3)
except RecursionError:
print("never reached the base case")Python stops this with a RecursionError once the chain of calls gets too deep. Later chapters explain that limit.
Moving in the wrong direction
factorial(n + 1) changes the input, but it moves away from 0. A negative argument to the correct factorial causes the same failure: factorial(-1) calls factorial(-2), and the measure n was never non-negative to begin with. Guard the inputs you don't support, either by raising an error or by widening the base case.
Stepping over the base case
When the reduction skips values, an equality test in the base case can be jumped right over:
def count_by_twos(n):
if n <= 0: # n == 0 would miss odd inputs: 3, 1, -1, ...
return 0
return 1 + count_by_twos(n - 2)
print(count_by_twos(7)) # 4With n == 0, an odd input passes 1 and keeps going negative. Using <= makes the base case cover every value the measure can land on.
Dropping the result
The recursive call runs, but its value is thrown away or never returned:
def sum_to_buggy(n):
if n == 0:
return 0
n + sum_to_buggy(n - 1) # missing return
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1)
print(sum_to(4)) # 10
try:
sum_to_buggy(4)
except TypeError as e:
print("TypeError:", e)sum_to_buggy(1) falls off the end and returns None. Its caller then computes 2 + None and fails. The bug is in one frame, but the error shows up in the frame above it, which makes this mistake harder to spot than it looks.
Combining incorrectly
The reduction can be perfect while the combine step is wrong. For example, return n + factorial(n - 1) terminates and returns a number, but it computes a sum instead of a product. To check the combine step, ask: "If the recursive call returns the correct answer for the smaller input, does this line produce the correct answer for the current input?" The next chapters return to this question as the basis of recursive thinking.
Checklist for a Recursive Case
- The smaller input is built from the current input and is valid for the function.
- A named measure strictly decreases on every recursive call.
- The base case covers every value where the measure stops shrinking, including values reached by skipping.
- Every path through the recursive case returns a value.
- The combine step is correct, assuming the recursive call is correct.
Exercise
This function is meant to count how many times n can be halved before reaching 1. Why does halvecount(6) never finish, and how do you fix it? def halvecount(n): if n == 1: return 0 return 1 + halve_count(n / 2)
Show answer
The / operator produces floats, so 6 becomes 3.0, then 1.5, 0.75, and so on. The value gets smaller but never equals 1, so the equality base case is stepped over and the recursion continues until RecursionError. Use integer division and a base case that covers everything at or below 1: if n <= 1: return 0 and return 1 + halve_count(n // 2). Now the measure n is a non-negative integer that strictly decreases, and halve_count(6) returns 2 (6 → 3 → 1).
Exercise
For gcd(a, b) shown in this chapter, explain why the recursion terminates even though the first argument can increase (for example, gcd(18, 48) calls gcd(48, 18)).
Show answer
The base case tests b, so b is the measure. Each call replaces b with a % b. For a positive b, the value a % b is a non-negative integer strictly less than b. A non-negative integer cannot decrease forever, so b eventually reaches 0, which is the base case. The first argument does not need to shrink, because termination depends only on the measure.