Sometimes an algorithm is slow because it repeats the same computation again and again. The solution is to save the result the first time and reuse it: you spend a little memory and gain a lot of time.
The problem: recursive Fibonacci
Fibonacci numbers are defined as fib(n) = fib(n-1) + fib(n-2). The direct recursive version is very short, but it computes the same thing many times: for fib(5), fib(3) is computed twice, fib(2) three times...
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(20), calls) # 6765 21891
To compute fib(20) it makes 21 891 calls, and for each step of *n* they are multiplied by about 1.6: it is exponential. fib(50) would take hours.
Memoization with a dictionary
Memoization stores each computed result in a dictionary. Before computing, it checks whether it is already there.
calls = 0
memo = {}
def fib(n):
global calls
calls += 1
if n in memo:
return memo[n]
result = n if n < 2 else fib(n - 1) + fib(n - 2)
memo[n] = result
return result
print(fib(20), calls) # 6765 39
print(fib(50)) # 12586269025
Now there are only 39 calls: the cost goes from exponential to linear. You will check it in Fibonacci with memoization.
functools.lru_cache: memoization without effort
The @lru_cache decorator does all of the above for you. You decorate the function and that is it. cache_info() also tells you how many times the cache hit or missed.
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(50)) # 12586269025
print(fib.cache_info()) # CacheInfo(hits=48, misses=51, maxsize=None, currsize=51)
Conditions to memoize: the function must be pure (same argument, same result, no side effects) and its arguments hashable (numbers, strings, tuples; not lists).
Dynamic programming: building bottom-up
Dynamic programming solves a big problem from smaller subproblems that repeat, storing their solutions. Memoization is the "top-down" (recursive) version; you can also go bottom-up, filling a table in order, without recursion.
def fib(n):
if n < 2:
return n
previous, current = 0, 1
for _ in range(n - 1):
previous, current = current, previous + current
return current
print(fib(50)) # 12586269025
This version uses only two variables: O(n) time and O(1) memory.
A classic example: coin change
What is the fewest number of coins to pay an amount? A table fewest[c] stores the answer for each amount c. The answer for c is 1 plus the best of the answers for c - coin.
def fewest_coins(coins, target):
INF = float("inf")
fewest = [0] + [INF] * target
for amount in range(1, target + 1):
for m in coins:
if m <= amount and fewest[amount - m] + 1 < fewest[amount]:
fewest[amount] = fewest[amount - m] + 1
return None if fewest[target] == INF else fewest[target]
print(fewest_coins([1, 3, 4], 6)) # 2 (3 + 3)
print(fewest_coins([2], 3)) # None
Greedy versus dynamic
A greedy algorithm chooses at each step what seems best at that moment, without looking back: for change, always take the largest coin possible. It is very fast, but it does not always give the best solution:
def greedy(coins, target):
total = 0
for m in sorted(coins, reverse=True):
total += target // m
target %= m
return total if target == 0 else None
print(greedy([1, 3, 4], 6)) # 3 (4 + 1 + 1) but 3 + 3 is 2!
print(greedy([1, 5, 10, 25], 63)) # 6 (with euros or cents it does work)
Compare both methods in Coin change. The important thing is to know they exist and choose according to the problem: greedy if it can be proven correct, dynamic when not.
When to apply memoization
- When a recursive function is called many times with the same arguments.
- When the computation is expensive and the result can be reused.
- When you can afford the memory to store the results.
With this you close a key idea of the course: efficiency is not just writing fewer lines, but choosing the algorithm and the data structure well.