Sub topic 6
Thinking Recursively: Trusting the Smaller Call
This chapter assumes you can write Python functions, read a base case and a recursive case, and trace a short recursive call through the call stack. Earlier chapters covered those mechanics. This one is about design: how to write a recursive function without tracing every call in your head.
Why Tracing Doesn't Scale
Tracing a call stack shows you how recursion runs. It is a poor way to design a recursive function. A trace of factorial(5) has five frames and is easy to follow. A trace of a function over a tree with a thousand nodes, or one that makes two calls per step, is too large to keep in your head. If you have to trace a function to believe it works, you can only write functions small enough to trace.
Experienced programmers reason a different way, called the recursive leap of faith. When you write the recursive case, you assume the recursive call already returns the correct answer for its smaller input. Then you ask one question: given that correct smaller answer, how do I build the answer for the current input?
The Leap of Faith, Stated Precisely
The leap of faith is a rule you can check, and it is safe when these three conditions hold:
- The base cases are correct. Every input that the function does not reduce further gets the right answer directly.
- Every recursive call is on a strictly smaller input, in a sense that eventually reaches a base case. Examples are a smaller number, a shorter list, or a subtree.
- The combining step is correct, assuming the recursive calls return correct results.
If all three hold, the function is correct for every input. This is proof by mathematical induction: the base case is the starting step, and the combining step is the inductive step. You don't have to write a proof, but this is why the leap is safe. You check each piece locally, and correctness follows for the whole function.
Worked Example: Sum of Digits
Goal: sum_digits(4096) should return 4 + 0 + 9 + 6 = 19.
Smallest input. A single-digit number (0 to 9) is its own digit sum. That is the base case.
How to shrink. n // 10 drops the last digit, and n % 10 gives that last digit. So 4096 splits into 409 and 6.
Leap of faith. Assume sum_digits(409) correctly returns 13. Don't check it.
Combine. The answer for 4096 is the last digit plus the digit sum of the rest: 6 + 13.
def sum_digits(n):
if n < 10:
return n
return n % 10 + sum_digits(n // 10)
print(sum_digits(4096)) # 19
print(sum_digits(7)) # 7Now check the three conditions. The base case is right for 0 to 9. n // 10 is strictly smaller than n for any n >= 10, so the input always shrinks until it falls below 10. If the inner call is correct, adding the last digit gives the correct total. Those three checks cover every non-negative integer without tracing anything.
Worked Example: Binary Representation
Goal: to_binary(13) should return "1101".
The leap of faith tells you which question to ask: if I already had the binary string for some smaller number, how would I get the binary string for n? In binary, n // 2 is n with its last bit removed, and n % 2 is that last bit. So the binary form of n is the binary form of n // 2 with one more character appended.
def to_binary(n):
if n < 2:
return str(n)
return to_binary(n // 2) + str(n % 2)
print(to_binary(13)) # 1101
print(to_binary(0)) # 0
print(to_binary(8)) # 1000Look at where the recursive call sits. In sum_digits, the order of the addition doesn't matter. Here the smaller result goes on the left because the high-order bits come first. The leap of faith frees you from tracking the calls, but you still have to think about how the pieces fit together.
Choosing How to Shrink
Often the input can shrink in more than one way, and the choice changes the cost. Here are two correct versions of integer exponentiation:
def power_linear(base, exp):
if exp == 0:
return 1
return base * power_linear(base, exp - 1)
def power_fast(base, exp):
if exp == 0:
return 1
half = power_fast(base, exp // 2)
if exp % 2 == 0:
return half * half
return half * half * base
print(power_linear(2, 10)) # 1024
print(power_fast(2, 10)) # 1024
print(power_fast(3, 5)) # 243Both pass the three checks. power_linear shrinks exp by 1, so it makes exp calls. power_fast halves exp, so it makes about log₂(exp) calls. For power_fast, the leap of faith works like this: assume power_fast(base, exp // 2) is correct, square it, and multiply by one extra base if exp is odd. Storing the result in half matters. Writing power_fast(base, exp // 2) * power_fast(base, exp // 2) would compute the same value twice and lose the speedup.
| Shrinking strategy | Calls for exp = 1,000,000 | Stack depth |
|---|---|---|
| `exp - 1` | 1,000,000 | 1,000,000 (fails in CPython) |
| `exp // 2` | about 20 | about 20 |
Common Errors
The leap of faith only holds when all three conditions hold. Most bugs in recursive functions break one of them.
The input doesn't actually shrink
def bad_sum_digits(n):
if n < 10:
return n
return n % 10 + bad_sum_digits(n) # same n, never reaches the base caseThe combining step looks plausible, but the call is not on a smaller input. Python eventually raises RecursionError. When you review a recursive function, point to the argument of each recursive call and say why it is smaller.
A base case is missing for some inputs
to_binary handles 0 and 1 because the test is n < 2. If the base case were n == 1, then to_binary(0) would call to_binary(0) forever. A related mistake is calling sum_digits(-5). The test -5 < 10 is true, so the function returns -5, which is not a digit sum. Decide which inputs are valid and check that every one of them reaches a correct base case.
Forgetting to return the combined result
def broken(n):
if n < 10:
return n
n % 10 + broken(n // 10) # value computed, then discardedbroken(42) returns None. broken(123) raises TypeError because the inner call returns None and Python tries to compute 2 + None. The recursive case must return its result.
Trusting the call while giving it the wrong job
The leap of faith assumes the smaller call does exactly what the function promises. If you mentally redefine the function partway through ("this call returns the last digit"), your combining step will be wrong. Write a one-line contract for the function, such as "returns the sum of the decimal digits of a non-negative integer n", and judge every recursive call against that contract.
Exercises
Exercise
Write countdigits(n) that returns the number of decimal digits in a non-negative integer, so countdigits(0) is 1 and count_digits(4096) is 4. State the base case, how the input shrinks, and the combining step.
Show answer
Base case: if n < 10, return 1. Shrink: n // 10 removes one digit. Combine: return 1 + countdigits(n // 10). Code: def countdigits(n): if n < 10: return 1; return 1 + count_digits(n // 10). For any n >= 10, n // 10 is smaller, so every call reaches the base case.
Exercise
Euclid's rule says gcd(a, b) = gcd(b, a % b) when b > 0, and gcd(a, 0) = a. Write gcd recursively and explain which argument gets smaller.
Show answer
def gcd(a, b): if b == 0: return a; return gcd(b, a % b). The second argument shrinks strictly, because a % b < b whenever b > 0. It cannot go below 0, so it eventually reaches the base case b == 0. Example: gcd(48, 18) leads to gcd(18, 12), then gcd(12, 6), then gcd(6, 0), which returns 6.
Exercise
A student writes def power(base, exp): if exp == 0: return 1; return power(base, exp // 2) power(base, exp // 2) (base if exp % 2 else 1). Is it correct, and is it fast?
Show answer
It is correct, because each call is on a smaller exponent and the combining step is right. It is not fast. It makes two recursive calls per level, so the total number of calls grows roughly in proportion to exp, which cancels the benefit of halving. Store one call's result in a variable and square it to get about log2(exp) calls.