The worst thing you can do when someone asks you to calculate binomial coefficients or Fibonacci numbers is to write a function that implements the definition of these objects from a schoolbook verbatim.
The straightforward approach looks like this:
def c(n, k):
if n == k or k == 0:
return 1
return c(n - 1, k - 1) + c(n - 1, k)
def f(n):
if n < 3:
return 1
return f(n - 1) + f(n - 2)
Due to a beautiful symmetry, the recurrence for the number of function calls is almost exactly the same as the one for the function itself. It means that the running time explodes exponentially. The simple remedy is to use cache or lru_cache from functools module or a hash table in other languages:
from functools import cache
@cache
def f(n):
if n < 3:
return 1
return f(n - 1) + f(n - 2)
from functools import lru_cache
@lru_cache(maxsize=128)
def f(n):
...
So, the worst solution for is . Let's think that k is around . The next improvement one can make is to consider as element of a table (Pascal's triangle) and build it literally. This gives and . That's better. Next trick - use two rows instead of the full table, reduces memory consumption \rightarrow . Factorial gym gives us, probably, the best solution $$T=O(n)M=O(1)
I like tricks like the one from the previous post. I don't like mundane things like watching out for catches when they ask you to calculate . In the middle of this row arithmetic explodes with almost , when it's totally feasible to compute.
OK, we know solution for . What about fibonacci? Next time.