Predict the output
What does this print?
from functools import cache
@cache
def ways(k: int) -> int:
return 1 if k <= 1 else ways(k - 1) + ways(k - 2)
print(ways(30), ways.cache_info().currsize)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 1346269 31
Right: 31 states (0 to 30) are each computed once.
The cache size equals the number of states, which is the number the cost estimate starts from.
Why not the others?
- B 832040 31. With ways(0) = ways(1) = 1, the value for 30 is 1346269.
- C 1346269 2692537. The cache stores one entry per state, not per call.