Standard library · 15 / 17 Exercise Medium

Memoization with lru_cache

Objective

The @lru_cache decorator from the functools module stores the results of a function so they are not recalculated. It also lets you see how many times it has reused the cache with cache_info().

Instructions

  • Define fib(n) recursively (fib(0) and fib(1) are 0 and 1) decorated with @lru_cache(maxsize=None).
  • Read an integer n and show fib(n) = value.
  • Then show Computed: m, the times the function was actually computed (cache_info().misses), and Reused: h, the times the stored result was returned (cache_info().hits).
Input
10
Output
fib(10) = 55
Computed: 11
Reused: 8

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise