Question 8
Back to Exercise
The program below stops with an error. Which statement correctly describes the problem?
from functools import lru_cache
@lru_cache(maxsize=None)
def total(nums):
return 0 if not nums else nums[0] + total(nums[1:])
print(total([3, 5, 7]))
- A It prints 15
- B RecursionError
- C TypeError: lru_cache uses the arguments as dict keys and a list is unhashable; pass a tuple, e.g. total((3, 5, 7)) Correct
- D IndexError
Correct Answer: Option C
With a tuple, slicing gives tuples too, so every recursive call stays hashable.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!