Editor

Memoization Decorator

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
def memoize(func):
# Your code here
pass
# Test your memoization
@memoize
def add(a, b):
return a + b
print(add(2, 3)) # 5
print(add(2, 3)) # 5 (from cache)

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.