A function that calls itself
🌍 In real life. Picture a set of nesting dolls. To find the smallest doll, you open the big one; inside is a smaller doll, so you do the same thing again: open it. You keep going until you reach a doll that doesn't open. That tiny one is the answer, and you never had to plan how many dolls there were.
A function that solves a problem by doing the same thing to a smaller piece of it is using recursion.
The idea in one sentence: a recursive function calls itself on a smaller version of the problem, until it reaches a base case small enough to answer straight away.
Its words:
- recursion: a function calling itself
- base case: the smallest case, answered without another call; it stops the recursion
- recursive case: the call on a smaller problem, like
fact(n - 1)
Step by step, for fact(3):
- 3 isn't the base case, so
fact(3)needs3 * fact(2), and waits. fact(2)needs2 * fact(1), and waits.fact(1)is the base case: it returns 1.- Now the waiting calls finish in reverse:
fact(2)returns 2, thenfact(3)returns 6.
def countdown(n):
if n == 0:
print("Liftoff!")
return
print(n)
countdown(n - 1)
countdown(3)A classic example is the factorial: 4! means 4 × 3 × 2 × 1. Notice that 4! is just 4 × 3!, and 3! is 3 × 2!, and so on down to 1! = 1. That is a recursive definition:
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(4))
print(fact(6))Why it works. If the base case is right, and each recursive call gets a smaller problem that still heads toward the base case, then every call eventually gets its answer. You only have to trust that the smaller call returns the right thing, and use it.
What it costs. fact(n) makes n calls, one after another, so it does about n steps, like a loop. Each waiting call also takes a little memory until it finishes, so a recursion n calls deep uses memory for n calls at once.
Mistakes and edge cases.
- No base case. The calls never stop:
RecursionError: maximum recursion depth exceeded(next lesson). - A problem that doesn't shrink.
fact(n)callingfact(n)again is the same mistake. - Forgetting return on the recursive call.
fact(n - 1)on its own works out the answer and throws it away, so the function gives backNone. - A base case that's never reached.
fact(-1)withif n == 0:skips past 0 forever;n <= 1is safer.
Quiz
What does this print?
def countdown(n): if n == 0: print("Go!") return print(n) countdown(n - 1) countdown(2)What does this print?
def fact(n): if n <= 1: return 1 return n * fact(n - 1) print(fact(3))What is a base case?
- The small case a recursive function answers without calling itself
- The first line of every function
- The biggest input the function can take
What does this print?
def total(n): if n == 0: return 0 return n + total(n - 1) print(total(4))Which line has a mistake?
def fact(n): if n <= 1: return 1 return n * fact(n) print(fact(3))
Coding tasks
Write a recursive
factorial(n)that returns n! (withfactorial(0)andfactorial(1)both 1).Write a recursive
sum_to(n)that returns 1 + 2 + … + n (and 0 forsum_to(0)).Write a recursive
power(base, exp)that returns base to the power exp, for exp 0 or more, without using**.