LearnFrenzy
Sign in Take a free test

Recursion · Find the Error · Question 8

Error: lru_cache with a list argument Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

The program below stops with an error. Which statement correctly describes the problem?

main.py
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links