August 2018
Intermediate to advanced
366 pages
10h 14m
English
Here are the steps for this recipe:
import functools
@functools.lru_cache(maxsize=None)
def fibonacci(n):
'''inefficient recursive version of Fibonacci number'''
if n > 1:
return fibonacci(n-1) + fibonacci(n-2)
return n
fibonacci_seq = [fibonacci(n) for n in range(100)]
>>> print(fibonacci_seq) [0, 1, 1, 2, 3, 5, 8, 13, 21 ...
The difference in performance is huge. If we use the timeit module to time our function, we can easily see how much memoizing helped with performance.