Editor

Write a Memoize Decorator

Advanced · Write the code · from 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

From the lesson: 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

Fifty problems, each with a code editor and real tests. Write your solution, press Check, and see exactly which cases pass. Stuck? Hints reveal one at a time, and the solution unlocks once you have checked at least once. Your code and progress are saved in this browser.

Read the lesson

Write a decorator memoize that caches a function's results by its positional arguments, so repeated calls return instantly. The decorated function must keep its original __name__. (Do not use functools.lru_cache or functools.cache.)

import functools
def memoize(func):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines. The output must match exactly.

RunsExpected output
calls = [] @memoize def square(n): calls.append(n) return n * n print(square(4), square(4), square(5), calls)16 16 25 [4, 5]

More practice problems

All Python exercises · 50 practice problems