
Remember the Answers
Some recursive functions solve the same subproblem again and again:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fib(5) calls fib(3) twice and fib(2) three times. The waste grows
explosively: fib(40) makes over 300 million calls!
Memoization fixes this: store each answer the first time and reuse it
afterwards. functools.lru_cache does it for you with one line:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(100)) # instant!
print(fib.cache_info()) # hits, misses, size
Now each fib(k) is computed only once, so the work grows linearly.
(functools.cache is a shortcut for lru_cache(maxsize=None).)
Pip tip: Caching only works for pure functions, where the same arguments always give the same result. The arguments must also be hashable (numbers, strings, tuples, but not lists).
Assignment
The Tribonacci numbers are like Fibonacci, but each one is the sum of the three before it:
tribonacci(0) == 0,tribonacci(1) == 0,tribonacci(2) == 1- otherwise
tribonacci(n) == tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3)
Write it recursively and decorate it with @lru_cache(maxsize=None) so that
tribonacci(100) is instant.
The Tribonacci numbers are like Fibonacci, but each one is the sum of the three before it:
tribonacci(0) == 0,tribonacci(1) == 0,tribonacci(2) == 1- otherwise
tribonacci(n) == tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3)
Write it recursively and decorate it with @lru_cache(maxsize=None) so that
tribonacci(100) is instant.
Press Run to try your code, then Check to test it.