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
- Write a memoized
fib(n)using@functools.lru_cache(maxsize=None), withfib(0) == 0andfib(1) == 1, otherwisefib(n) == fib(n-1) + fib(n-2). - Write
fib_list(n)that returns the list[fib(0), fib(1), ..., fib(n-1)]β that is, the firstnFibonacci 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.