Sub topic 1
What Makes a Function Recursive
A recursive function is a function that calls itself to solve a smaller version of the same problem. This chapter gives you the working model behind that idea and the mistakes that most often break it. Later chapters apply the model to factorial, Fibonacci, and powers.
Prerequisites
This chapter assumes you can already do the following:
- Write and call functions in Python.
- Use conditionals (
if/else) and loops. - Do integer arithmetic, including integer division (
//) and remainder (%). - Read Big-O notation for running time, such as O(n) and O(log n).
The Two Parts of Every Recursive Definition
Every correct recursive function has two parts.
- Base case: an input small enough to answer directly, with no further calls.
- Recursive case: a rule that expresses the answer for a larger input in terms of the answer for a smaller one.
The recursive case has to move the input toward the base case. If it never gets there, the function never stops.
Take the sum of a list. The sum of an empty list is 0, which is the base case. The sum of any other list is its first element plus the sum of the rest, which is the recursive case. The rest of the list is shorter, so every call gets closer to the empty list.
def sum_list(items):
if not items: # base case: empty list
return 0
return items[0] + sum_list(items[1:]) # recursive case: shorter list
print(sum_list([3, 1, 4, 1, 5])) # 14Reading a Recursive Definition
Many definitions in mathematics are already recursive. Before you write any code, find the two parts in the definition.
| Definition | Base case | Recursive case | Measure that shrinks |
|---|---|---|---|
| Sum of a list | `sum([]) = 0` | `sum(xs) = xs[0] + sum(xs[1:])` | List length |
| Factorial | `0! = 1` | `n! = n * (n-1)!` | n |
| Fibonacci | `F(0) = 0`, `F(1) = 1` | `F(n) = F(n-1) + F(n-2)` | n |
| Power | `x^0 = 1` | `x^n = x * x^(n-1)` | n |
The last column matters most. Choose a quantity, usually a size or a count, that gets strictly smaller with every call and cannot go below the base case. If you can name that quantity, you know the recursion ends.
Common Errors
These errors show up most often:
- Missing base case. The function calls itself forever until Python raises
RecursionError. - Input that does not shrink. Calling
f(n)from insidef(n), orf(n + 1)when the base case is at 0, never reaches the base case. - Skipping past the base case. If the base case is
n == 0and the recursive call usesn - 2, an oddnjumps from 1 to -1 and keeps going. - Inputs outside the domain. A negative
nnever reachesn == 0by subtracting 1. Reject such inputs explicitly or handle them as their own case. - Throwing away the recursive result. Writing
sum_list(items[1:])withoutreturnand without combining it givesNoneor a wrong answer.
def countdown(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0: # base case
print("Liftoff")
return
print(n)
countdown(n - 1) # n shrinks by 1 each call
countdown(3) # prints 3, 2, 1, LiftoffRecursion Versus Loops
Any recursive function can be rewritten as a loop, and any loop can be rewritten as recursion. Recursion fits best when the problem breaks naturally into smaller copies of itself. Each recursive call also uses memory until it returns. The next chapter covers the call stack, which explains that cost.
Exercise
Identify the base case, the recursive case, and the shrinking measure for this function. Then say what happens when it is called with countdigits(-5) and how you would fix it. def countdigits(n): if n < 10: return 1 return 1 + count_digits(n // 10)
Show answer
The base case is n < 10, which returns 1. The recursive case is 1 + countdigits(n // 10). The shrinking measure is the number of digits in n, because n // 10 drops one digit. For -5, the base case n < 10 is true, so the function returns 1 and gives the right answer by accident. For a value like -123, it also returns 1, which is wrong, because every negative number counts as less than 10. To fix it, add "if n < 0: return countdigits(-n)" before the base case.
Exercise
A student writes def total(n): return n + total(n - 1) to sum 1 through n. What is wrong, and what is the corrected function?
Show answer
The function has no base case, so it keeps calling itself with smaller and smaller numbers until Python raises RecursionError. Corrected version: def total(n): if n == 0: return 0, then return n + total(n - 1). Also reject negative n, because subtracting 1 from a negative number never reaches 0.