Problem No 20
Write a decorator that memoizes function results
Hard≈ 30 minute session
Lesson guide
What this Python exercise practices
Write a decorator that memoizes function results is a advanced practice lesson that focuses on dsa, problem patterns, edge cases. It is designed to be solved in about 30 minutes with examples, starter code, and test feedback.
Prerequisites
- Python functions
- Loops
- Lists
- Basic edge cases
Difficulty and time
- Level
- Advanced
- Estimated time
- 30 minutes
Summary
Create a decorator that caches function return values to avoid repeated work. Apply it to a recursive function to improve performance.
Problem statement
Memoization is a common technique to speed up functions by caching results of expensive calls and returning the cached result when the same inputs occur again. Your task is to implement a decorator named memoize that stores the results of function calls keyed by the function's arguments (both positional and keyword). The decorator should: - Cache results per-decorated-function (each function has its own cache). - Support arbitrary positional and keyword arguments as cache keys. - Return cached values when the same arguments are seen again. - Work correctly with recursive functions (i.e., the decorated function should call the wrapper when recursing so cached results are used). Apply this decorator to a recursive Fibonacci function provided in the starter code. Do not change the function signature of the decorated functions. The tests will call the decorated fib function to verify correct memoization and results.
Task
Implement a memoization decorator that caches results based on positional and keyword arguments, preserves function behavior, and works with recursive functions.
Examples
Simple usage on Fibonacci
Input
fib(6)
Output
8
Explanation
fib(0)=0, fib(1)=1, fib(2)=1, fib(3)=2, fib(4)=3, fib(5)=5, fib(6)=8. The memoize decorator caches intermediate results so computing fib(6) is fast.
Input format
A single expression calling the decorated function (e.g., fib(10)).
Output format
The function's return value converted to a string.
Constraints
- Cache keys must account for both args and kwargs. - The decorator should not change the function's return values or side effects (other than caching performance). - The solution must be pure Python and self-contained using only the standard library.
Samples
Sample input 0
fib(5)
Sample output 0
5
Explanation 0
Returns the 5th Fibonacci number (0-indexed) which is 5.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.