Hand-Rolled Memoization

Medium ⏱ 12 min 48% acceptance ★★★★★ 4.9
Write memoize(func) caching results in a dict keyed by the positional arguments tuple — repeat calls with the same args skip the computation. Then note in discussion that functools.lru_cache is the production version (bounded, thread-aware).

Examples

Example 1
Input
@memoize on slow_square; slow_square(4); slow_square(4)
Output
16 both times, computed once
Explanation

The second call was a dict hit.

Constraints

  • Cache key: the args tuple (kwargs out of scope).
  • The cache lives in the closure.

Topics

Decoratorscaching

Companies

GoogleMetaBloomberg

Hints

Hint 1

if args in cache: return cache[args].

Hint 2

Store before returning.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.