Skip to content

17. Memoize a Function

Difficulty: Medium · Topic: Functions & decorators

Write a decorator memoize that caches results: when the decorated function is called again with the same arguments, return the stored result without running the function.

In the sample, slow_square(4) runs once and the second call comes from the cache, so the function runs only twice in all: len(calls) is 2.

Your code runs in CPython on our servers against 5 tests, including hidden ones.

Sample test

calls = []

@memoize
def slow_square(x):
    calls.append(x)
    return x * x

[slow_square(4), slow_square(4), slow_square(5), len(calls)]

Expected: [16, 16, 25, 2]

Hints

Hint 1Keep a dict in the decorator's closure, keyed by the arguments.
Hint 2A key that includes keyword arguments: (args, tuple(sorted(kwargs.items()))).
Hint 3Test membership with key in cache, not by the cached value being truthy.

Learn the concepts

More Python problems

All Python problems