The problem of repeating calculations
Recursive Fibonacci recalculates the same values over and over again:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(20)) # 6765
For fib(35) this version makes almost 30 million calls. The solution is memoization: store each result in a dictionary and reuse it:
memory = {}
def fib(n):
if n in memory:
return memory[n]
if n < 2:
result = n
else:
result = fib(n - 1) + fib(n - 2)
memory[n] = result
return result
print(fib(50)) # 12586269025
Now each value is computed only once, and fib(50) is instant. Python offers this technique ready-made with functools.cache:
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(50)) # 12586269025
The two-pointer technique
In a sorted list, two indexes, one at the start and one at the end, moving towards each other, solve many problems without needing two nested loops. For example, finding two numbers that add up to a value:
def pair(items, target):
i = 0
j = len(items) - 1
while i < j:
s = items[i] + items[j]
if s == target:
return items[i], items[j]
elif s < target:
i += 1 # we need a larger sum
else:
j -= 1 # we need a smaller sum
return None
print(pair([1, 3, 4, 6, 8, 11], 10)) # (4, 6)
print(pair([1, 2, 3], 10)) # None
At each step you safely rule out one possibility, because the list is sorted. You go through the list only once.
Measuring efficiency
To compare algorithms, you count how many operations they do depending on the input size n. The most common cases:
| Growth | Example | If n doubles… |
|---|---|---|
| Logarithmic | Binary search | One more step |
| Linear | Linear search, minimum and maximum | Twice the work |
| Quadratic | Bubble, selection, insertion | Four times the work |
You can also measure real time with time.perf_counter():
import time
start = time.perf_counter()
total = sum(range(1_000_000))
end = time.perf_counter()
print(total) # 499999500000
print(end - start < 5) # True
The exact time changes from one computer to another; the growth of the algorithm does not. That is why it is preferred to reason about how many steps it takes.
Practice with Fibonacci with memory and Pair with a given sum.