Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Write a decorator that memoizes function results

Create a decorator that caches function return values to avoid repeated work. Apply it to a recursive function to improve performance.

Python practice30 minFunctions & ScopeAdvancedLast updated March 17, 2026

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

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 1

Input

fib(5)

Output

5

Returns the 5th Fibonacci number (0-indexed) which is 5.