← Practice
πŸ“– The functools modulefunctools-memo-fib
LessonΒ·difficulty 3/5Β·~20 min

functools: memoized Fibonacci

functools: memoized Fibonacci

Naive recursive Fibonacci is famously slow β€” it recomputes the same values an exponential number of times. functools.lru_cache fixes that with one line: it remembers each result, so every fib(n) is computed at most once.

python
import functools

@functools.lru_cache(maxsize=None)
def fact(n):
    return 1 if n == 0 else n * fact(n - 1)

fact(5)   # 120, and intermediate results are cached

Slap the decorator on a recursive function and the recursion stays simple while the performance becomes linear. That's memoization for free.

Your task

  1. Write a memoized fib(n) using @functools.lru_cache(maxsize=None), with fib(0) == 0 and fib(1) == 1, otherwise fib(n) == fib(n-1) + fib(n-2).
  2. Write fib_list(n) that returns the list [fib(0), fib(1), ..., fib(n-1)] β€” that is, the first n Fibonacci numbers.
python
fib_list(7)    # [0, 1, 1, 2, 3, 5, 8]
fib_list(1)    # [0]
fib_list(0)    # []   (zero numbers requested)
fib_list(10)   # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Hint: fib_list(n) is just [fib(i) for i in range(n)].

Tests

  • first seven
  • just zero
  • none requested
  • first ten
  • single fib (hidden)
  • first two (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.