Predict the output
What does this print?
calls = 0
def plain(k: int) -> int:
global calls
calls += 1
return 1 if k <= 1 else plain(k - 1) + plain(k - 2)
print(plain(10), calls)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 89 177
Right: 89 ways, but the uncached recursion makes 177 calls.
The call count grows like the answer itself, exponentially, while the cached version makes about n calls.
Why not the others?
- B 89 11. That would be the cached call count, roughly one per value.
- C 55 109. With ways(0) = 1 the answer for 10 stones is 89.
Steps come from running the Python solution.
Text version
Without a cache:
- 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 a cache:
- 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)