Editor

Memoization Decorator

#25 · Functions · Advanced · 100 XP · about 10 min

Write a function called memoize(func) that returns a memoized version of the input function. Memoization caches the results of function calls so repeated calls with the same arguments return the cached result.

Example

@memoize
def slow_square(x):
    return x ** 2

slow_square(4)  # Returns 16 (computed)
slow_square(4)  # Returns 16 (cached, fast!)
slow_square(5)  # Returns 25 (computed)

Requirements

  • Cache results based on the function arguments
  • Return cached result if available
  • Work with functions that take any number of positional arguments

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.