Predict the output
What does this print?
calls = 0
def ways(n: int) -> int:
global calls
calls += 1
return 1 if n <= 1 else ways(n - 1) + ways(n - 2)
ways(20)
print(calls)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 21891
Right: the call tree grows roughly by a factor of 1.6 per level.
Over twenty thousand calls for n = 20 is the exponential call tree that memoisation collapses to about n calls.
Why not the others?
- B 21. With a memo it would be about n calls; without one the tree branches.
- C 40. Each call spawns two more until the base case, so calls grow exponentially.
Illustrative
Text version
No memo:
- ways(5): call
- ways(4): call
- ways(3): call
- ways(2): call
- ways(1): call
- ways(0): call
- ways(1): call
- ways(2): call
- ways(2): call
- ways(1): call
- ways(0): call
- ways(3): call
- ways(3): call
- ways(2): call
- ways(1): call
- ways(0): call
- ways(1): call
- ways(2): call
- ways(4): call
Result: 8 · 15 calls (call 15)
With memo:
- ways(5): call
- ways(4): call
- ways(3): call
- ways(2): call
- ways(1): call
- ways(0): call
- ways(1): memo hit
- ways(2): call
- ways(2): memo hit
- ways(3): call
- ways(3): memo hit
- ways(4): call
Result: 8 · 9 calls (call 6, memo hit 3)