Part 2. Mathematics first, then the algorithm#
In part 1 the formula \(n^2(n-1)\) turned out to be more than ten thousand times faster than the double loop. This is not an exception but the rule: the largest speedups come not from writing a loop better, but from not computing certain things at all. This kind of laziness pays off the most. In this part we will see it in five guises: a formula instead of a loop, memoizing the results of a recursion, memoization in a loop, a better parametrization, and a smarter search. The examples come from Lectures 1 and 5 and from the book by T. Altenkirch and I. Triguero, Conceptual Programming with Python (2020): binomial coefficients computed recursively and sudoku solved by backtracking.
import math
from functools import cache
import sympy as sp
srodowisko("sympy")
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11, sympy 1.14.0
A formula instead of a loop: sums of powers#
In Lecture 5 (§5.3) we guessed the formulas for the sums \(S_p(n)=1^p+2^p+\dots+n^p\) by interpolation and proved them by induction. SymPy knows these formulas, because it can sum symbolically:
k, n = sp.symbols("k n", integer=True, positive=True)
for p in (1, 3, 5):
print(f"S_{p}(n) =", sp.factor(sp.summation(k**p, (k, 1, n))))
S_1(n) = n*(n + 1)/2
S_3(n) = n**2*(n + 1)**2/4
S_5(n) = n**2*(n + 1)**2*(2*n**2 + 2*n - 1)/12
Let us compare summing cubes in a loop with the formula \(S_3(n)=\bigl(n(n+1)/2\bigr)^2\). We evaluate the formula in integer arithmetic, so the result is exact for every \(n\).
def szesciany_petla(n):
s = 0
for k in range(1, n + 1):
s += k**3
return s
def szesciany_sum(n):
return sum(k**3 for k in range(1, n + 1))
def szesciany_wzor(n):
return (n * (n + 1) // 2)**2
czasy_potegi = porownaj({"pętla": szesciany_petla,
"sum z generatorem": szesciany_sum,
"wzór (n(n+1)/2)²": szesciany_wzor}, 10**6)
wariant czas przyspieszenie
pętla 41.4 ms 1.0×
sum z generatorem 49.6 ms 0.84×
wzór (n(n+1)/2)² 75.1 ns 551828×
The loop performs a million multiplications and additions, and the formula a few operations, so the formula is more than a hundred thousand times faster. With \(n\) ten times larger, the loop will be ten times slower, while the time of the formula will hardly change. The numbers in it do get longer, but they have only a few dozen digits. So before we start speeding up a loop, it is worth asking whether it can be avoided.
Recursion and memoization: binomial coefficients#
Altenkirch and Triguero derive a recurrence for the number of ways to choose \(m\) balls out of \(n\). We look at the ball with the largest number: either we take it (it remains to choose \(m-1\) out of \(n-1\)), or we do not (it remains to choose \(m\) out of \(n-1\)). Hence
The program follows directly from the formula:
def dwumian(n, m):
if m == 0:
return 1
if n == 0:
return 0
return dwumian(n - 1, m) + dwumian(n - 1, m - 1)
print("dwumian(24, 6) =", dwumian(24, 6),
" math.comb(24, 6) =", math.comb(24, 6))
dwumian(24, 6) = 134596 math.comb(24, 6) = 134596
The program is correct, but it computes the same values many times. For example, it computes \(\binom{n-2}{m-1}\) twice: once via \(\binom{n-1}{m}\), and a second time via \(\binom{n-1}{m-1}\). How many calls does it make for various arguments? The number of calls \(L(n,m)\) satisfies the same recurrence as the binomial coefficient itself, only plus one for the current call. We will compute it with memoization (more on that in a moment), because otherwise counting the calls would take as long as making them.
@cache
def wywolania(n, m):
"""Liczba wywołań funkcji dwumian(n, m), łącznie z pierwszym."""
if m == 0 or n == 0:
return 1
return 1 + wywolania(n - 1, m) + wywolania(n - 1, m - 1)
t_wywolania = zmierz(dwumian, 24, 6) / wywolania(24, 6)
for n_, m_ in ((24, 6), (30, 6), (49, 6)):
L = wywolania(n_, m_)
print(f"C({n_},{m_}) = {math.comb(n_, m_):>10}: wywołań {L:>11},",
f"szacowany czas {czas(L * t_wywolania)}")
C(24,6) = 134596: wywołań 380101, szacowany czas 8.54 ms
C(30,6) = 593775: wywołań 1536423, szacowany czas 34.5 ms
C(49,6) = 13983816: wywołań 32244451, szacowany czas 724 ms
The number of calls grows together with the result: every leaf of the recursion tree returns \(0\) or \(1\), so there are at least \(\binom{n}{m}\) leaves. The time estimate is the number of calls multiplied by the average time of one call, measured for \(\binom{24}{6}\). For \(\binom{49}{6}\), that is, the number of possible outcomes of a Lotto draw, it takes tens of millions of calls and a time on the order of a second. In the book by Altenkirch and Triguero, published in 2020, the same computation took “a few seconds.”
The remedy is “lazy” in the best sense: we remember the values already computed. The decorator
functools.cache attaches a dictionary (arguments → result) to the function. Each pair \((n,m)\) is
then computed once, so there are \(O(nm)\) calls instead of exponentially many. This is the same
decorator that sped up the computation of Fibonacci numbers in Lecture 1
(§1.2), there in its older form
lru_cache(maxsize=None).
@cache
def dwumian_pamiec(n, m):
if m == 0:
return 1
if n == 0:
return 0
return dwumian_pamiec(n - 1, m) + dwumian_pamiec(n - 1, m - 1)
def dwumian_od_nowa(n, m):
dwumian_pamiec.cache_clear() # mierzymy liczenie, a nie odczyt
return dwumian_pamiec(n, m)
def dwumian_silnie(n, m):
return math.factorial(n) // (math.factorial(m) * math.factorial(n - m))
czasy_dwumian = porownaj({"rekurencja": dwumian,
"rekurencja + @cache": dwumian_od_nowa,
"silnie": dwumian_silnie,
"math.comb": math.comb}, 24, 6)
print("C(49, 6) z pamięcią:", dwumian_od_nowa(49, 6))
wariant czas przyspieszenie
rekurencja 8.51 ms 1.0×
rekurencja + @cache 14.1 µs 602×
silnie 199 ns 42734×
math.comb 29.0 ns 292958×
C(49, 6) z pamięcią: 13983816
The single line @cache speeds up the recursion more than a hundred times, and \(\binom{49}{6}\) is
now computed in a fraction of a millisecond. The fastest, however, is the ready-made function
math.comb from the standard library. It is written in C and uses product formulas rather than
Pascal’s recurrence. This is another rung of laziness: before we write a function, we check whether
it is already in a library (part 4).
When memoization helps
A cache helps when the function is pure: its result depends only on its arguments, and a call
changes nothing outside it. The function dwumian is pure. A function that reads a global variable
or draws random numbers is not, and its remembered result may be out of date. The arguments must
also be hashable (numbers, strings, tuples — but not lists). The memory used grows with the number
of distinct arguments, and lru_cache(maxsize=...) bounds it by evicting the least recently used
entries.
Memoization in a loop: Collatz steps#
In Lecture 1 we computed Collatz trajectories: \(n\mapsto n/2\) for even numbers, \(n\mapsto3n+1\) for odd ones, until we reach \(1\). In Lab 8 we plot the number of steps for all \(n\le3000\). The trajectories of different numbers merge quickly; for example, the trajectory of \(6\) passes through \(3\). The number of steps for \(3\) is then already known and does not have to be computed a second time.
def kroki(n):
k = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
k += 1
return k
def kroki_wszystkie(N):
return [kroki(n) for n in range(1, N + 1)]
def kroki_slownik(N):
"""To samo z pamięcią: słownik liczba → liczba kroków."""
znane = {1: 0}
for start in range(2, N + 1):
droga, n = [], start
while n not in znane: # idziemy do pierwszej znanej liczby
droga.append(n)
n = n // 2 if n % 2 == 0 else 3 * n + 1
k = znane[n]
for m in reversed(droga): # i uzupełniamy drogę od końca
k += 1
znane[m] = k
return [znane[n] for n in range(1, N + 1)]
@cache
def kroki_pamiec(n):
if n == 1:
return 0
return 1 + kroki_pamiec(n // 2 if n % 2 == 0 else 3 * n + 1)
def kroki_cache(N):
kroki_pamiec.cache_clear()
return [kroki_pamiec(n) for n in range(1, N + 1)]
N = 10**5
czasy_collatz = porownaj({"każda liczba osobno": kroki_wszystkie,
"słownik znanych wyników": kroki_slownik,
"@cache": kroki_cache}, N)
wynik = kroki_cache(N)
rekord = max(range(N), key=wynik.__getitem__)
print(f"najwięcej kroków dla n ≤ {N}: {wynik[rekord]} (n = {rekord + 1})")
wariant czas przyspieszenie
każda liczba osobno 331 ms 1.0×
słownik znanych wyników 29.8 ms 11×
@cache 24.0 ms 14×
najwięcej kroków dla n ≤ 100000: 350 (n = 77031)
Memoization makes the computation many times faster. The version with a dictionary shows what happens
inside: we walk along the trajectory to the first number whose number of steps is known, and then
fill in the path backward from its end. The version with @cache does the same with a single
decorator, but recursively. The recursion depth here equals the length of the longest unknown path,
and this does not exceed the record number of steps (a few hundred). That is less than Python’s
recursion limit:
import sys
print("limit rekurencji:", sys.getrecursionlimit())
limit rekurencji: 1000
For longer paths, the version with a dictionary, which uses no recursion, would be safer.
A better parametrization: Pythagorean triples#
In Lecture 1 we found the primitive Pythagorean triples with \(c<30\) by a triple loop over \(a<b<c\). Such a loop checks about \(c^3/6\) triples. Euclid gives a parametrization: for coprime \(m>k\ge1\) of opposite parity, the triple
is a primitive Pythagorean triple, and every primitive triple arises in this way exactly once (up to swapping \(a\) and \(b\)). SymPy will check the identity \((m^2-k^2)^2+(2mk)^2=(m^2+k^2)^2\):
m, k = sp.symbols("m k")
print(sp.expand((m**2 - k**2)**2 + (2*m*k)**2 - (m**2 + k**2)**2) == 0)
True
def trojki_petle(C):
return {(a, b, c)
for c in range(1, C) for b in range(1, c) for a in range(1, b)
if a*a + b*b == c*c and math.gcd(a, b) == 1}
def trojki_euklides(C):
wynik = set()
m = 2
while m * m + 1 < C:
for k in range(1, m):
if (m - k) % 2 == 1 and math.gcd(m, k) == 1 and m*m + k*k < C:
a, b = m*m - k*k, 2*m*k
wynik.add((min(a, b), max(a, b), m*m + k*k))
m += 1
return wynik
czasy_trojki = porownaj({"trzy pętle": trojki_petle,
"parametryzacja Euklidesa": trojki_euklides}, 150)
print("trójek z c < 150:", len(trojki_euklides(150)),
"| z c < 10^6:", len(trojki_euklides(10**6)))
print(f"potrójna pętla dla c < 10^6 sprawdziłaby",
f"{math.comb(10**6 - 1, 3):.2e} trójek")
wariant czas przyspieszenie
trzy pętle 14.7 ms 1.0×
parametryzacja Euklidesa 5.67 µs 2588×
trójek z c < 150: 24 | z c < 10^6: 159139
potrójna pętla dla c < 10^6 sprawdziłaby 1.67e+17 trójek
Both methods give the same set (porownaj checks this), but the parametrization is more than
a hundred times faster already for \(c<150\). For \(c<10^6\) the triple loop would have to check about
\(1.7\cdot10^{17}\) triples, which cannot be done. The parametrization enumerates all the triples in
a fraction of a second, because it goes through only the pairs \((m,k)\) with \(m^2<c\). A mathematical
theorem has turned a search into an enumeration.
A smarter search: sudoku#
Altenkirch and Triguero solve sudoku by backtracking: they write the first digit allowed by the rules into the first empty cell and move on. When some cell has no allowed digit, they go back and try the next digit in an earlier cell. Let us write the same program and count the attempts, that is, the digits written into cells.
ZAGADKI = { # wiersze planszy, 0 oznacza puste pole
"łatwa": ("530070000" "600195000" "098000060"
"800060003" "400803001" "700020006"
"060000280" "000419005" "000080079"),
"trudna": ("800000000" "003600000" "070090000"
"050007000" "000045700" "000100030"
"001000068" "008500010" "090000400"),
}
def plansza(napis):
return [[int(napis[9 * w + k]) for k in range(9)] for w in range(9)]
def napis(P):
return "".join(str(c) for wiersz in P for c in wiersz)
def mozna_wpisac(P, w, k, c):
if c in P[w] or any(P[i][k] == c for i in range(9)):
return False
w0, k0 = 3 * (w // 3), 3 * (k // 3)
return all(P[w0 + i][k0 + j] != c for i in range(3) for j in range(3))
def nawroty(zagadka):
"""Pierwsze puste pole, cyfry po kolei. Zwraca (rozwiązanie, próby)."""
P, proby = plansza(zagadka), 0
def krok():
nonlocal proby
for w in range(9):
for k in range(9):
if P[w][k] == 0:
for c in range(1, 10):
if mozna_wpisac(P, w, k, c):
proby += 1
P[w][k] = c
if krok():
return True
P[w][k] = 0
return False # żadna cyfra nie pasuje: cofamy się
return True # brak pustych pól: rozwiązane
krok()
return napis(P), proby
The second version changes two things. For each row, column, and box it keeps the set of digits already used, so checking a digit is a lookup in a set instead of a scan of 27 cells. More importantly, it starts with the cell that has the fewest allowed digits. It fills in a cell with only one possibility at once, without guessing, and when some cell has none, it backtracks immediately.
def nawroty_najmniej_mozliwosci(zagadka):
"""Najpierw pole o najmniejszej liczbie kandydatów.
Zwraca (rozwiązanie, liczba prób).
"""
P, proby = plansza(zagadka), 0
wiersze = [set(P[w]) for w in range(9)]
kolumny = [{P[w][k] for w in range(9)} for k in range(9)]
kwadraty = [{P[w][k] for w in range(9) for k in range(9)
if 3 * (w // 3) + k // 3 == b} for b in range(9)]
puste = [(w, k) for w in range(9) for k in range(9) if P[w][k] == 0]
cyfry = set(range(1, 10))
def kandydaci(w, k):
kwadrat = kwadraty[3 * (w // 3) + k // 3]
return cyfry - wiersze[w] - kolumny[k] - kwadrat
def krok():
nonlocal proby
if not puste:
return True
i = min(range(len(puste)), key=lambda i: len(kandydaci(*puste[i])))
w, k = puste.pop(i)
grupy = (wiersze[w], kolumny[k], kwadraty[3 * (w // 3) + k // 3])
for c in kandydaci(w, k):
proby += 1
P[w][k] = c
for g in grupy:
g.add(c)
if krok():
return True
for g in grupy:
g.remove(c)
P[w][k] = 0
puste.insert(i, (w, k))
return False
krok()
return napis(P), proby
def poprawne(rozwiazanie, zagadka):
"""Kontroler: cyfry 1–9 w każdym wierszu, kolumnie i kwadracie.
Pola dane w zagadce muszą zostać bez zmian.
"""
P = plansza(rozwiazanie)
wiersze = [P[w] for w in range(9)]
kolumny = [[P[w][k] for w in range(9)] for k in range(9)]
kwadraty = [[P[w][k] for w in range(9) for k in range(9)
if 3 * (w // 3) + k // 3 == b] for b in range(9)]
grupy = wiersze + kolumny + kwadraty
return (all(sorted(g) == list(range(1, 10)) for g in grupy)
and all(z in "0" + r for z, r in zip(zagadka, rozwiazanie)))
czasy_sudoku = {}
for nazwa, zagadka in ZAGADKI.items():
for metoda in (nawroty, nawroty_najmniej_mozliwosci):
rozwiazanie, proby = metoda(zagadka)
assert poprawne(rozwiazanie, zagadka)
czasy_sudoku[nazwa, metoda.__name__] = t = zmierz(metoda, zagadka)
print(f"{nazwa:7} {metoda.__name__:28} prób: {proby:7}",
f" czas: {czas(t)}")
łatwa nawroty prób: 4208 czas: 12.0 ms
łatwa nawroty_najmniej_mozliwosci prób: 51 czas: 417 µs
trudna nawroty prób: 132575 czas: 396 ms
trudna nawroty_najmniej_mozliwosci prób: 1053 czas: 14.9 ms
Both versions solve the easy puzzle (the same one that Altenkirch and Triguero solve) quickly. For
the hard puzzle, plain backtracking needs more than a hundred thousand attempts, while the version
that starts with the cell with the fewest candidates needs over a hundred times fewer and runs a few
dozen times faster. The checker poprawne verifies each solution independently of the method that
found it. This is the same division of roles as throughout the course: the search may be clever or
not, but the result is checked by a simple program.
The order in which we search through the possibilities determines the running time far more than the speed of a single step. We will see the same lesson in Lectures 7 and 8. The geometry engine (Lecture 7) and proof search in Peano Lab (Lecture 8) also search huge trees. There, a language model is in essence a hint about which branch to start with. P. Norvig writes more about sudoku in this spirit in his essay Solving Every Sudoku Puzzle, where he combines constraint propagation with choosing the cell that has the fewest candidates.
Summary#
First we ask whether we need to compute at all: a formula for a sum of powers replaces a loop, Euclid’s parametrization replaces a search.
A recursion that computes the same values many times needs a cache: the single line
@functools.cacheturns exponential time into polynomial time. We memoize only pure functions.In a search, a good order gives the most: the most constrained decisions first.
The result of a clever algorithm is verified by a simple checker (
poprawne, the comparison of variants inporownaj).
Exercises#
★ Write
fib(n)without memoization and with@cache. Measure both variants for \(n=20, 25, 30\). By what factor does the time of the version without memoization grow when \(n\) grows by \(5\)? Compare with \(\varphi^5\), where \(\varphi=(1+\sqrt5)/2\).★★ Prove that the function
dwumian(n, m)makes exactly \(L(n,m)=2\sum_{j=0}^{m}\binom{n}{j}-1\) calls. Hint: the function \((L+1)/2\) satisfies Pascal’s recurrence. Check the formula with the functionwywolaniafor a few pairs \((n,m)\).★★ Count the primitive Pythagorean triples with \(c<N\) for \(N=10^3,10^4,10^5,10^6\) and compare with \(N/(2\pi)\).
★★ Add to
nawroty_najmniej_mozliwoscia counter of the cells filled in “without guessing” (with a single candidate). What fraction of all attempts is this for each of the two puzzles?