Cache a Factorial Function
Intermediate · Write the code · from Python functools: lru_cache, partial, reduce, singledispatch
From the lesson: Python functools: lru_cache, partial, reduce, singledispatch
Imagine your functions could remember past answers, come pre-loaded with some arguments, or automatically handle different data types. That's what the functools module gives you: power-ups for your functions.
Read the lessonWrite a recursive factorial(n) function decorated with @lru_cache(maxsize=None). It should return 1 if n <= 1, otherwise n * factorial(n - 1). Print factorial(10) and then print the cache info.
from functools import lru_cache
# Write a cached factorial function
# Print factorial(10)
# Print cache_info()
More functools exercises
- Create a Percentage Calculator with partialIntermediate
- Reduce a List to Find the MaximumIntermediate
- Predict the partial OutputBeginner
- Build a String with reduceAdvanced
- Create a singledispatch FormatterAdvanced
- Fix the Caching BugAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz