How does one dictionary that remembers answers already computed collapse eleven million Fibonacci calls into sixty-five?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
The memo d arrives in the state the video starts it in: the two base cases, and nothing else. Fibonacci of 3 is not in it yet.
Work out Fibonacci of 3 from the two values already sitting in d — build it out of the stored entries rather than typing the answer as a literal — then store it in d under the key n. Assign the updated dictionary to memo.
The memo dictionary mapping n to fib(n)
Write the initialization d = {1:1, 2:1} and state that the two original base cases sit in the dictionary as pre-loaded entries keyed by n.
fib_efficient and its lookup base case
Copy out fib_efficient(n, d) with its if n in d: return d[n] base case and a recursive step that saves ans, stores d[n] = ans, then returns ans.
Trace of fib_efficient(6)
Trace the descent to the base cases and list the dictionary after each store, 3 to 2, 4 to 3, 5 to 5 and 6 to 8, marking the calls never made.
The space-for-time trade-off
Record the figures for fib(34), over 11.4 million calls unmemoized against 65 calls and 34 dictionary entries memoized, plus the case for recalculating instead of storing.