Sub topic 6
Thinking Recursively: Trusting the Smaller Call
This chapter assumes you can read simple Python, know what a base case and a recursive case are, and have traced a call stack by hand. Tracing proves a function works on one input. To design a new recursive function, you need a different habit: the recursive leap of faith.
The Leap of Faith
The leap of faith means you assume the recursive call already returns the correct answer for the smaller input. You don't follow it down the stack. Your only job is to turn that smaller answer into the answer for the current input.
This is safe for the same reason induction works in math. Suppose the base case is correct, and each step builds a correct answer from a correct smaller answer. Then every input that eventually reaches the base case is handled correctly.
A Four-Step Design Recipe
- State in one sentence what the function returns.
- Choose the smallest input and return its answer directly.
- Pick a smaller input and assume the call on it is correct.
- Combine that result with the leftover piece to get the full answer.
Apply the recipe to sum_digits(n), which adds up the decimal digits of a non-negative integer.
sum_digits(n)returns the sum of the digits ofn.- A single digit (
n < 10) is its own sum. n // 10drops the last digit, so assumesum_digits(n // 10)is correct.- Add back the dropped digit,
n % 10.
def sum_digits(n):
if n < 10:
return n
return sum_digits(n // 10) + n % 10
print(sum_digits(4096)) # 19You never traced sum_digits(409) or sum_digits(40). You only checked that 409's digit sum plus 6 equals 4096's digit sum.
Choosing a Good Smaller Problem
The smaller problem doesn't have to be "n minus one." Pick whatever reduction makes the combine step easy. In power(x, n), halving n gives a short combine step and far fewer calls:
def power(x, n):
if n == 0:
return 1
half = power(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
print(power(2, 10)) # 1024Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Tracing every call while designing | You get lost after a few levels | Check one level, then trust the call |
| No one-sentence statement of the result | The combine step returns the wrong kind of value | Write the sentence first |
| The input doesn't actually shrink | Infinite recursion, then `RecursionError` | Make sure every call moves toward the base case |
| Base case misses some inputs | Wrong answer for small values | Test the smallest inputs directly |
Exercise
Using the four-step recipe, write countdigits(n), which returns how many decimal digits a non-negative integer n has (countdigits(0) is 1). State the smaller problem you trust and the combine step.
Show answer
The smallest case is n < 10, which returns 1. Trust countdigits(n // 10), which counts every digit except the last one, and add 1 to it: def countdigits(n): return 1 if n < 10 else countdigits(n // 10) + 1. For example, countdigits(4096) returns 4.
Exercise
A student writes def sumdigits(n): return sumdigits(n // 10) + n % 10 with no if statement. Which step of the recipe was skipped, and what happens when the function runs?
Show answer
Step 2, the base case, is missing. Once n reaches 0, the call becomes sum_digits(0) over and over because 0 // 10 is still 0, so Python raises RecursionError.