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.

Hide code cell source

# Narzędzia pomiaru czasu — opisane w części 1 tego rozdziału.
import platform
import statistics
import subprocess
import sys
import textwrap
import timeit
from importlib.metadata import version

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter

INDYGO, BURSZTYN, ZIELEN = "#4f46e5", "#d97706", "#059669"
SZARY, TUSZ, SIATKA = "#94a3b8", "#334155", "#e2e8f0"
JEDNOSTKI = (("s", 1.0), ("ms", 1e-3), ("µs", 1e-6), ("ns", 1e-9))


def zmierz(f, *args, cel=0.02, proby=7):
    """Mediana czasu jednego wywołania f(*args), w sekundach.

    Szybką funkcję wywołujemy w seriach trwających około `cel` sekund, bo
    zegar nie zauważy pojedynczego wywołania trwającego ułamek mikrosekundy.
    Z `proby` serii bierzemy medianę, odporną na serie zakłócone przez inne
    programy.
    """
    zegar = timeit.Timer(lambda: f(*args))
    t = zegar.timeit(number=1)          # rozgrzewka i pierwsza ocena
    if t > cel:                         # wolna funkcja: trzy wywołania
        return statistics.median(zegar.repeat(repeat=3, number=1))
    n = 1
    while t < cel / 10:                 # zbyt krótka seria: wydłużamy ją
        n *= 10
        t = zegar.timeit(number=n)
    n = max(1, round(n * cel / t))      # seria trwa teraz około `cel` s
    return statistics.median(zegar.repeat(repeat=proby, number=n)) / n


def czas(s):
    """Czas w sekundach jako napis z jednostką, np. 1.23 ms."""
    for jednostka, skala in JEDNOSTKI:
        if s >= 0.9995 * skala or jednostka == "ns":
            v = s / skala
            if v >= 99.95:
                return f"{v:.0f} {jednostka}"
            return f"{v:#.3g} {jednostka}"


def krotnosc(r):
    """Iloraz czasów jako napis: 340×, 2.5×, 0.81×."""
    if r >= 10:
        return f"{r:.0f}×"
    return f"{r:.1f}×" if r >= 1 else f"{r:.2f}×"


def porownaj(warianty, *args, zgodne=None):
    """Mierzy warianty (nazwa → funkcja) na tych samych danych.

    Najpierw sprawdza, że wszystkie warianty dają ten sam wynik (operatorem
    == albo funkcją `zgodne`): porównujemy tylko programy, które liczą to
    samo. Przyspieszenie to czas pierwszego wariantu podzielony przez czas
    danego. Zwraca słownik czasów.
    """
    wyniki = {nazwa: f(*args) for nazwa, f in warianty.items()}
    wzorzec = next(iter(wyniki.values()))
    for nazwa, w in wyniki.items():
        if not (zgodne(w, wzorzec) if zgodne else w == wzorzec):
            raise AssertionError(f"wariant „{nazwa}” daje inny wynik")
    czasy = {nazwa: zmierz(f, *args) for nazwa, f in warianty.items()}
    baza = next(iter(czasy.values()))
    szer = max(len(nazwa) for nazwa in czasy)
    wiersze = [f"{'wariant':{szer}}  {'czas':>9}  {'przyspieszenie':>14}"]
    for nazwa, t in czasy.items():
        wiersze.append(f"{nazwa:{szer}}  {czas(t):>9}"
                       f"  {krotnosc(baza / t):>14}")
    print("\n".join(wiersze))
    return czasy


def srodowisko(*biblioteki):
    """Wypisuje, na czym mierzymy: procesor, system, Python, biblioteki."""
    if sys.platform == "darwin":
        procesor = subprocess.run(
            ["sysctl", "-n", "machdep.cpu.brand_string"],
            capture_output=True, text=True).stdout.strip()
        system = f"macOS {platform.mac_ver()[0]}"
    else:
        procesor = platform.processor()
        system = f"{platform.system()} {platform.release()}"
    opis = [procesor or platform.machine(), system,
            f"Python {platform.python_version()}"]
    opis += [f"{b} {version(b)}" for b in biblioteki]
    print(textwrap.fill("Pomiary: " + ", ".join(opis), width=79,
                        subsequent_indent="  "))


def upewnij(warunek, tresc):
    """Pilnuje zdań z tekstu rozdziału.

    Gdy pomiar przeczy zdaniu, budowa książki się zatrzymuje.
    """
    if not warunek:
        raise AssertionError(f"Tekst rozdziału twierdzi: {tresc}. "
                             "Pomiar temu przeczy.")


def _os_czasu(v, _):
    for jednostka, skala in JEDNOSTKI:
        if v >= 0.9995 * skala:
            return f"{v / skala:.0f} {jednostka}"
    return f"{v / 1e-9:g} ns"


def wykres_czasow(czasy, tytul):
    """Czasy wariantów na osi logarytmicznej; najszybszy jest wyróżniony."""
    nazwy = list(czasy)[::-1]           # pierwszy wariant na górze
    t = [czasy[nazwa] for nazwa in nazwy]
    fig, ax = plt.subplots(figsize=(8, 0.42 * len(nazwy) + 1.2))
    ax.scatter(t, range(len(nazwy)), s=70, zorder=3, edgecolors="white",
               linewidths=2, c=[INDYGO if v == min(t) else SZARY for v in t])
    for i, v in enumerate(t):
        ax.annotate(czas(v), (v, i), xytext=(9, 0), va="center",
                    textcoords="offset points", fontsize=9, color=TUSZ)
    ax.set_yticks(range(len(nazwy)), nazwy)
    ax.set_xscale("log")
    ax.set_xlim(min(t) / 3, max(t) * 8)  # miejsce na etykiety
    ax.xaxis.set_major_locator(LogLocator(base=10))
    ax.xaxis.set_major_formatter(FuncFormatter(_os_czasu))
    ax.xaxis.set_minor_formatter(NullFormatter())
    ax.grid(axis="x", color=SIATKA, lw=1)
    ax.set_axisbelow(True)
    for bok in ("top", "right", "left"):
        ax.spines[bok].set_visible(False)
    ax.tick_params(axis="y", length=0)
    ax.set_title(tytul, loc="left", fontsize=11)
    plt.tight_layout()
    plt.show()


def wykres_skalowania(rozmiary, serie, tytul, opis_x="n"):
    """Czas w zależności od rozmiaru danych, obie osie logarytmiczne."""
    fig, ax = plt.subplots(figsize=(8, 4))
    style = zip(serie.items(), (INDYGO, BURSZTYN, ZIELEN), "osD")
    for (nazwa, czasy_serii), kolor, znak in style:
        ax.loglog(rozmiary, czasy_serii, "-", marker=znak, color=kolor,
                  lw=2, ms=6, label=nazwa)
    ax.set_xticks(rozmiary, [str(n) for n in rozmiary])
    ax.xaxis.set_minor_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(FuncFormatter(_os_czasu))
    ax.yaxis.set_minor_formatter(NullFormatter())
    ax.set_xlabel(opis_x)
    ax.grid(color=SIATKA, lw=1)
    ax.set_axisbelow(True)
    for bok in ("top", "right"):
        ax.spines[bok].set_visible(False)
    ax.legend(loc="best", frameon=False, fontsize=9)
    ax.set_title(tytul, loc="left", fontsize=11)
    plt.tight_layout()
    plt.show()
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

\[ \binom{n}{m}=\binom{n-1}{m}+\binom{n-1}{m-1},\qquad \binom{n}{0}=1,\qquad \binom{0}{m}=0\ \text{for}\ m>0. \]

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

\[ a=m^2-k^2,\qquad b=2mk,\qquad c=m^2+k^2 \]

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.cache turns 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 in porownaj).

Exercises#

  1. ★ 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\).

  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 function wywolania for a few pairs \((n,m)\).

  3. ★★ Count the primitive Pythagorean triples with \(c<N\) for \(N=10^3,10^4,10^5,10^6\) and compare with \(N/(2\pi)\).

  4. ★★ Add to nawroty_najmniej_mozliwosci a 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?