Fibonacci and Memoization
The Fibonacci numbers start 0, 1, 1, 2, 3, 5, 8, ...: each number is the sum of the two before it. fib(0) is 0 and fib(1) is 1.
Write fib(n) that returns the n-th Fibonacci number for n >= 0. The tests include fib(38) and fib(400), so the first version you write will be too slow.
Understand the problem
Count the work of the obvious recursive version.
Using fib(n) = fib(n - 1) + fib(n - 2), what is fib(6)? (The sequence is 0, 1, 1, 2, 3, 5, ...)
The sequence continues 0, 1, 1, 2, 3, 5, 8: fib(6) = fib(5) + fib(4) = 5 + 3.
How many times is fib(2) computed when you compute fib(5) with the plain recursive version?
fib(5) calls fib(4) and fib(3). fib(4) calls fib(3) and fib(2); fib(3) calls fib(2) and fib(1). So fib(2) is reached 3 times, and fib(3) twice. The same small problems are solved again and again.
Write the brute force
Write the simplest version that is correct, even if it is slow. Then you have something to test against and something to improve.
def fib(n):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
Which two small problems does fib(n) depend on, and what are the answers for n = 0 and n = 1?
Hint 2: the shape of the answer
Return n if n < 2. Otherwise return fib(n - 1) + fib(n - 2).
Find the bottleneck
Why is this slow, and what fixes it?
The number of calls of the plain version grows by about a factor of 1.6 for every step in n. For n = 38, about how many calls?
- About 100
- About 100,000
- About 100 million
The call count is roughly 1.6 to the power n: for n = 38 it is about 126 million calls. That takes many seconds. The growth is exponential: every extra step multiplies the work.
How can you avoid solving the same small problem many times?
- Use a bigger computer
- Remember each answer the first time (a dictionary), and look it up afterwards
- Call the function in a loop
This is memoization: store the result of fib(k) in a dictionary the first time, and return the stored value on every later call. Each value is then computed once, so the work is linear in n.
Make it faster
Remember the results. Python offers a decorator for it, but write it yourself first.
def fib(n):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
Where can you store results so they survive between the recursive calls?
Hint 2: the pattern
A dictionary outside the function, or a default argument such as memo=None that you fill in. Check the dictionary first, store before returning.
Hint 3: pseudocode
memo = {}
def fib(n):
if n is in memo: return memo[n]
if n < 2: result = n
else: result = fib(n - 1) + fib(n - 2)
memo[n] = result
return result
Reflect
Brute force: exponential
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Improved: memoization with lru_cache
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Another way: a dictionary you manage yourself
memo = {}
def fib(n):
if n not in memo:
memo[n] = n if n < 2 else fib(n - 1) + fib(n - 2)
return memo[n]
Another way: a loop, no recursion
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
What this tests: recursion, why naive recursion can be exponential, memoization, functools.lru_cache, and tuple assignment (a, b = b, a + b).
Memoization in one sentence: never solve the same sub-problem twice. It is the heart of dynamic programming.
Three good answers: memoized recursion (reads like the definition), a loop (fastest and with no recursion limit), and @lru_cache (one line). In an interview, show the plain recursion first, explain why it is slow, then fix it.
Cost:
| Version | Time | Space |
|---|---|---|
| Plain recursion | exponential, about 1.6 to the power n | O(n) stack |
| Memoized or loop | O(n) | O(n) or O(1) |
Python integers have no limit, so fib(400) is exact, with 84 digits.
What an interviewer might ask next: Compute fib(10**6) fast. (Matrix exponentiation or fast doubling gives O(log n) steps.)
VISIBLE = 3
CASES = [
((0,), 0, 'the first number'),
((1,), 1, 'the second number'),
((2,), 1, 'two'),
((10,), 55, 'ten'),
((20,), 6765, 'twenty'),
((25,), 75025, 'twenty-five'),
((5,), 5, 'five'),
]
def REFERENCE(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
LIMIT = 2.0
def PERF():
return [('fib(38)', (38,)), ('fib(90)', (90,)), ('fib(400)', (400,))]