Which fix removes the bug?
from functools import lru_cache
@lru_cache(maxsize=None)
def total(items):
return sum(items)
total([1, 2, 3]) # TypeError
- Use
@lru_cache(maxsize=128) - Add
typed=Trueto the decorator - Pass a tuple:
total((1, 2, 3)) - Return
sum(list(items))instead
lru_cache hashes the arguments to build its cache key, and a list is unhashable. A tuple is hashable and sums the same way.
Play Problem Solving ▸