Sub topic 2
Recursion: Base Cases and Recursive Cases
This chapter assumes you can write and call functions, use for and while loops, and work with Python lists. The previous chapter showed repetition with loops. Here you will see how a function can repeat work by calling itself.
The two parts of every recursive function
A recursive function is a function that calls itself to solve a smaller version of the same problem. Every correct recursive function has two parts:
- The base case is an input small enough to answer directly, with no further calls. It stops the recursion.
- The recursive case handles any other input. It reduces the problem to a smaller one, calls the function on that smaller input, and combines the result.
Factorial is the standard example. By definition, 0! = 1 and n! = n × (n − 1)!. Each part of that definition maps to one part of the function:
def factorial_recursive(n):
if n == 0: # base case
return 1
return n * factorial_recursive(n - 1) # recursive case
def factorial_iterative(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_recursive(5)) # 120
print(factorial_iterative(5)) # 120Comparing the two versions shows how they correspond. The base case's return value, 1, plays the same role as the loop's starting value, result = 1. The recursive case's n * ... does the same job as the loop's update step, result *= i.
Making progress toward the base case
A base case only helps if every chain of calls eventually reaches it. Each recursive call must move the input closer to the base case. Usually that means a smaller number, a shorter list, or a smaller subtree.
Lists work the same way. The empty list is the base case, and each call handles one element and recurses on the rest:
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])) # 14A useful way to check a recursive function is to assume that the recursive call returns the correct answer for the smaller input. Then ask whether the current call combines it correctly. If sum_list(items[1:]) returns the sum of the rest, adding items[0] gives the full sum. This reasoning is induction, and it lets you check the function without tracing every call.
Common errors
| Error | Example | What happens |
|---|---|---|
| Missing base case | No `if n == 0` check | Calls never stop, so Python raises `RecursionError` |
| No progress | `factorial_recursive(n)` instead of `n - 1` | Same input forever, so `RecursionError` |
| Base case that some inputs skip past | `factorial_recursive(-1)` counts down past 0 | Never reaches 0, so `RecursionError` |
| Wrong base value | `return 0` for `n == 0` | Every result becomes 0 |
| Recursive result not returned | `factorial_recursive(n - 1)` without `return` | Function returns `None`, so it raises `TypeError` |
Exercise
Write a recursive function count_down_length(s) that returns the length of a string s without using len. Name its base case and recursive case.
Show answer
def countdownlength(s): if s == "": return 0 (base case: the empty string has length 0); otherwise return 1 + countdownlength(s[1:]) (recursive case: one character plus the length of the shorter rest). Each call removes one character, so the input always reaches the empty string.
Exercise
This function is meant to compute 2 to the power n for n >= 0: def poweroftwo(n): if n == 1: return 2; return 2 * poweroftwo(n - 1). What is wrong with it, and how do you fix it?
Show answer
The base case skips n == 0. poweroftwo(0) calls poweroftwo(-1) and counts down forever until RecursionError. Change the base case to if n == 0: return 1, which handles 0 and still gives the right answer for every positive n.