Fibonacci, stairs and remembering answers
🌍 In real life. If a friend asks you "what's 37 × 48?" and you work it out on paper, you'd be silly to work it out again when they ask a minute later; you'd just read your note. Writing an answer down so you never compute it twice is one of the most powerful tricks in programming.
The idea in one sentence: a recursive function that calls itself twice can repeat the same work again and again, and a memo dictionary that remembers each answer makes it fast.
Its words:
- Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, …, each the sum of the two before
- overlapping subproblems: the same smaller question asked many times
- memo (memoisation): a dictionary from question to answer, checked before working anything out
Step by step, for fib(4) without a memo:
fib(4)needsfib(3)andfib(2).fib(3)needsfib(2)andfib(1): sofib(2)is now being worked out twice.- For bigger n, the repeats multiply:
fib(20)makes over 20,000 calls.
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print([fib(n) for n in range(10)])But this does the same work again and again: fib(5) works out fib(3) twice and fib(2) three times. Count the calls:
calls = 0
def fib(n):
global calls
calls += 1
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print(fib(20), "took", calls, "calls")The fix is to remember answers in a dictionary, often called a memo. Before working something out, look it up; after working it out, store it. Each answer is then worked out only once:
def fib(n, memo):
if n <= 1:
return n
if n in memo:
return memo[n]
memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
return memo[n]
print(fib(80, {}))The same shape counts the ways to climb stairs taking 1 or 2 steps at a time: to reach step n, your last move came from step n - 1 or step n - 2, so ways(n) = ways(n - 1) + ways(n - 2).
What it costs, worked out. Without a memo, each call makes two more, so the number of calls nearly doubles every time n goes up by one: fib(20) takes 21,891 calls, and fib(40) would take over 300 million. With a memo, each fib(k) is worked out once and then looked up, so fib(n) takes about n steps: fib(80) above is instant. The memo costs memory for n answers, a very good trade.
Mistakes and edge cases.
- Storing but never checking. A memo only helps if you look it up before working anything out.
- A shared default memo.
def fib(n, memo={}):makes one dictionary for every call ever (Lesson 14.4); pass{}in, as above, unless you mean to share it. - The wrong base cases.
fib(0)is 0 andfib(1)is 1; getting either wrong shifts every answer. - Very large n. Even with a memo, the recursion is n calls deep, so
fib(5000)hits the RecursionError; a loop that keeps the last two numbers has no limit.
Quiz
What does this print?
def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2) print(fib(6))Why is the plain recursive
fibslow for big n?- It works out the same smaller answers again and again
- Adding numbers is slow in Python
- It has no base case
What does this print?
memo = {} def square(n): if n in memo: return "remembered " + str(memo[n]) memo[n] = n * n return memo[n] print(square(4)) print(square(4))What does this print?
def ways(n): if n <= 2: return n return ways(n - 1) + ways(n - 2) print(ways(4))Which line has a mistake?
def fib(n): if n == 0: return 0 return fib(n - 1) + fib(n - 2) print(fib(5))
Coding tasks
Write a recursive
fib(n)that returns the nth Fibonacci number, withfib(0)= 0 andfib(1)= 1.Write
stairs(n): the number of ways to climb n stairs (n ≥ 1) taking 1 or 2 steps at a time.Write
fast_fib(n, memo)that remembers answers in the dictionary memo, so evenfast_fib(60, {})is quick.