Cache an Expensive Lookup

Medium ⏱ 12 min 56% acceptance ★★★★★ 4.9
Write a class LookupCache with a dict-based cache and a method get(self, key, compute_fn). On the first call for a given key, call compute_fn(key), store the result in the cache, and return it. On subsequent calls with the same key, return the cached value without calling compute_fn again.

Examples

Example 1
Input
c = LookupCache(); c.get(4, lambda k: k * k)   # calls compute_fn
c.get(4, lambda k: 1/0)          # cache hit, no call, no error
Output
16 then 16
Explanation

Second call reuses the cached 16, even though the second compute_fn would raise.

Constraints

  • compute_fn must not be called again for a cached key.

Topics

Dictionariescaching

Companies

AdobeCisco

Hints

Hint 1

Store an internal `self._cache = {}`.

Hint 2

Use `if key not in self._cache: self._cache[key] = compute_fn(key)` then return `self._cache[key]`.

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