{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "65401313",
   "metadata": {},
   "source": [
    "# Part 2. Mathematics first, then the algorithm\n",
    "\n",
    "In part 1 the formula $n^2(n-1)$ turned out to be more than ten thousand times faster than the\n",
    "double loop. This is not an exception but the rule: the largest speedups come not from writing a loop\n",
    "better, but from not computing certain things at all. This kind of laziness pays off the most. In\n",
    "this part we will see it in five guises: a formula instead of a loop, memoizing the results of\n",
    "a recursion, memoization in a loop, a better parametrization, and a smarter search. The examples\n",
    "come from Lectures 1 and 5 and from the book by T. Altenkirch and I. Triguero, *Conceptual\n",
    "Programming with Python* (2020): binomial coefficients computed recursively and sudoku solved by\n",
    "backtracking."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa114917",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "# Narzędzia pomiaru czasu — opisane w części 1 tego rozdziału.\n",
    "import platform\n",
    "import statistics\n",
    "import subprocess\n",
    "import sys\n",
    "import textwrap\n",
    "import timeit\n",
    "from importlib.metadata import version\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter\n",
    "\n",
    "INDYGO, BURSZTYN, ZIELEN = \"#4f46e5\", \"#d97706\", \"#059669\"\n",
    "SZARY, TUSZ, SIATKA = \"#94a3b8\", \"#334155\", \"#e2e8f0\"\n",
    "JEDNOSTKI = ((\"s\", 1.0), (\"ms\", 1e-3), (\"µs\", 1e-6), (\"ns\", 1e-9))\n",
    "\n",
    "\n",
    "def zmierz(f, *args, cel=0.02, proby=7):\n",
    "    \"\"\"Mediana czasu jednego wywołania f(*args), w sekundach.\n",
    "\n",
    "    Szybką funkcję wywołujemy w seriach trwających około `cel` sekund, bo\n",
    "    zegar nie zauważy pojedynczego wywołania trwającego ułamek mikrosekundy.\n",
    "    Z `proby` serii bierzemy medianę, odporną na serie zakłócone przez inne\n",
    "    programy.\n",
    "    \"\"\"\n",
    "    zegar = timeit.Timer(lambda: f(*args))\n",
    "    t = zegar.timeit(number=1)          # rozgrzewka i pierwsza ocena\n",
    "    if t > cel:                         # wolna funkcja: trzy wywołania\n",
    "        return statistics.median(zegar.repeat(repeat=3, number=1))\n",
    "    n = 1\n",
    "    while t < cel / 10:                 # zbyt krótka seria: wydłużamy ją\n",
    "        n *= 10\n",
    "        t = zegar.timeit(number=n)\n",
    "    n = max(1, round(n * cel / t))      # seria trwa teraz około `cel` s\n",
    "    return statistics.median(zegar.repeat(repeat=proby, number=n)) / n\n",
    "\n",
    "\n",
    "def czas(s):\n",
    "    \"\"\"Czas w sekundach jako napis z jednostką, np. 1.23 ms.\"\"\"\n",
    "    for jednostka, skala in JEDNOSTKI:\n",
    "        if s >= 0.9995 * skala or jednostka == \"ns\":\n",
    "            v = s / skala\n",
    "            if v >= 99.95:\n",
    "                return f\"{v:.0f} {jednostka}\"\n",
    "            return f\"{v:#.3g} {jednostka}\"\n",
    "\n",
    "\n",
    "def krotnosc(r):\n",
    "    \"\"\"Iloraz czasów jako napis: 340×, 2.5×, 0.81×.\"\"\"\n",
    "    if r >= 10:\n",
    "        return f\"{r:.0f}×\"\n",
    "    return f\"{r:.1f}×\" if r >= 1 else f\"{r:.2f}×\"\n",
    "\n",
    "\n",
    "def porownaj(warianty, *args, zgodne=None):\n",
    "    \"\"\"Mierzy warianty (nazwa → funkcja) na tych samych danych.\n",
    "\n",
    "    Najpierw sprawdza, że wszystkie warianty dają ten sam wynik (operatorem\n",
    "    == albo funkcją `zgodne`): porównujemy tylko programy, które liczą to\n",
    "    samo. Przyspieszenie to czas pierwszego wariantu podzielony przez czas\n",
    "    danego. Zwraca słownik czasów.\n",
    "    \"\"\"\n",
    "    wyniki = {nazwa: f(*args) for nazwa, f in warianty.items()}\n",
    "    wzorzec = next(iter(wyniki.values()))\n",
    "    for nazwa, w in wyniki.items():\n",
    "        if not (zgodne(w, wzorzec) if zgodne else w == wzorzec):\n",
    "            raise AssertionError(f\"wariant „{nazwa}” daje inny wynik\")\n",
    "    czasy = {nazwa: zmierz(f, *args) for nazwa, f in warianty.items()}\n",
    "    baza = next(iter(czasy.values()))\n",
    "    szer = max(len(nazwa) for nazwa in czasy)\n",
    "    wiersze = [f\"{'wariant':{szer}}  {'czas':>9}  {'przyspieszenie':>14}\"]\n",
    "    for nazwa, t in czasy.items():\n",
    "        wiersze.append(f\"{nazwa:{szer}}  {czas(t):>9}\"\n",
    "                       f\"  {krotnosc(baza / t):>14}\")\n",
    "    print(\"\\n\".join(wiersze))\n",
    "    return czasy\n",
    "\n",
    "\n",
    "def srodowisko(*biblioteki):\n",
    "    \"\"\"Wypisuje, na czym mierzymy: procesor, system, Python, biblioteki.\"\"\"\n",
    "    if sys.platform == \"darwin\":\n",
    "        procesor = subprocess.run(\n",
    "            [\"sysctl\", \"-n\", \"machdep.cpu.brand_string\"],\n",
    "            capture_output=True, text=True).stdout.strip()\n",
    "        system = f\"macOS {platform.mac_ver()[0]}\"\n",
    "    else:\n",
    "        procesor = platform.processor()\n",
    "        system = f\"{platform.system()} {platform.release()}\"\n",
    "    opis = [procesor or platform.machine(), system,\n",
    "            f\"Python {platform.python_version()}\"]\n",
    "    opis += [f\"{b} {version(b)}\" for b in biblioteki]\n",
    "    print(textwrap.fill(\"Pomiary: \" + \", \".join(opis), width=79,\n",
    "                        subsequent_indent=\"  \"))\n",
    "\n",
    "\n",
    "def upewnij(warunek, tresc):\n",
    "    \"\"\"Pilnuje zdań z tekstu rozdziału.\n",
    "\n",
    "    Gdy pomiar przeczy zdaniu, budowa książki się zatrzymuje.\n",
    "    \"\"\"\n",
    "    if not warunek:\n",
    "        raise AssertionError(f\"Tekst rozdziału twierdzi: {tresc}. \"\n",
    "                             \"Pomiar temu przeczy.\")\n",
    "\n",
    "\n",
    "def _os_czasu(v, _):\n",
    "    for jednostka, skala in JEDNOSTKI:\n",
    "        if v >= 0.9995 * skala:\n",
    "            return f\"{v / skala:.0f} {jednostka}\"\n",
    "    return f\"{v / 1e-9:g} ns\"\n",
    "\n",
    "\n",
    "def wykres_czasow(czasy, tytul):\n",
    "    \"\"\"Czasy wariantów na osi logarytmicznej; najszybszy jest wyróżniony.\"\"\"\n",
    "    nazwy = list(czasy)[::-1]           # pierwszy wariant na górze\n",
    "    t = [czasy[nazwa] for nazwa in nazwy]\n",
    "    fig, ax = plt.subplots(figsize=(8, 0.42 * len(nazwy) + 1.2))\n",
    "    ax.scatter(t, range(len(nazwy)), s=70, zorder=3, edgecolors=\"white\",\n",
    "               linewidths=2, c=[INDYGO if v == min(t) else SZARY for v in t])\n",
    "    for i, v in enumerate(t):\n",
    "        ax.annotate(czas(v), (v, i), xytext=(9, 0), va=\"center\",\n",
    "                    textcoords=\"offset points\", fontsize=9, color=TUSZ)\n",
    "    ax.set_yticks(range(len(nazwy)), nazwy)\n",
    "    ax.set_xscale(\"log\")\n",
    "    ax.set_xlim(min(t) / 3, max(t) * 8)  # miejsce na etykiety\n",
    "    ax.xaxis.set_major_locator(LogLocator(base=10))\n",
    "    ax.xaxis.set_major_formatter(FuncFormatter(_os_czasu))\n",
    "    ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.grid(axis=\"x\", color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\", \"left\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.tick_params(axis=\"y\", length=0)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def wykres_skalowania(rozmiary, serie, tytul, opis_x=\"n\"):\n",
    "    \"\"\"Czas w zależności od rozmiaru danych, obie osie logarytmiczne.\"\"\"\n",
    "    fig, ax = plt.subplots(figsize=(8, 4))\n",
    "    style = zip(serie.items(), (INDYGO, BURSZTYN, ZIELEN), \"osD\")\n",
    "    for (nazwa, czasy_serii), kolor, znak in style:\n",
    "        ax.loglog(rozmiary, czasy_serii, \"-\", marker=znak, color=kolor,\n",
    "                  lw=2, ms=6, label=nazwa)\n",
    "    ax.set_xticks(rozmiary, [str(n) for n in rozmiary])\n",
    "    ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.yaxis.set_major_formatter(FuncFormatter(_os_czasu))\n",
    "    ax.yaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.set_xlabel(opis_x)\n",
    "    ax.grid(color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.legend(loc=\"best\", frameon=False, fontsize=9)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34421b63",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "from functools import cache\n",
    "\n",
    "import sympy as sp\n",
    "\n",
    "srodowisko(\"sympy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e440fce",
   "metadata": {},
   "source": [
    "## A formula instead of a loop: sums of powers\n",
    "\n",
    "In Lecture 5 (§5.3) we guessed the formulas for the sums $S_p(n)=1^p+2^p+\\dots+n^p$ by\n",
    "interpolation and proved them by induction. SymPy knows these formulas, because it can sum\n",
    "symbolically:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f7c6769",
   "metadata": {},
   "outputs": [],
   "source": [
    "k, n = sp.symbols(\"k n\", integer=True, positive=True)\n",
    "for p in (1, 3, 5):\n",
    "    print(f\"S_{p}(n) =\", sp.factor(sp.summation(k**p, (k, 1, n))))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93c8a4fd",
   "metadata": {},
   "source": [
    "Let us compare summing cubes in a loop with the formula $S_3(n)=\\bigl(n(n+1)/2\\bigr)^2$. We evaluate\n",
    "the formula in integer arithmetic, so the result is exact for every $n$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "182f7866",
   "metadata": {},
   "outputs": [],
   "source": [
    "def szesciany_petla(n):\n",
    "    s = 0\n",
    "    for k in range(1, n + 1):\n",
    "        s += k**3\n",
    "    return s\n",
    "\n",
    "\n",
    "def szesciany_sum(n):\n",
    "    return sum(k**3 for k in range(1, n + 1))\n",
    "\n",
    "\n",
    "def szesciany_wzor(n):\n",
    "    return (n * (n + 1) // 2)**2\n",
    "\n",
    "\n",
    "czasy_potegi = porownaj({\"pętla\": szesciany_petla,\n",
    "                         \"sum z generatorem\": szesciany_sum,\n",
    "                         \"wzór (n(n+1)/2)²\": szesciany_wzor}, 10**6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62c03497",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_potegi[\"pętla\"] > 10**5 * czasy_potegi[\"wzór (n(n+1)/2)²\"],\n",
    "        \"wzór na sumę sześcianów jest ponad sto tysięcy razy szybszy od pętli\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f165b19",
   "metadata": {},
   "source": [
    "The loop performs a million multiplications and additions, and the formula a few operations, so the\n",
    "formula is more than a hundred thousand times faster. With $n$ ten times larger, the loop will be ten\n",
    "times slower, while the time of the formula will hardly change. The numbers in it do get longer, but\n",
    "they have only a few dozen digits. So before we start speeding up a loop, it is worth asking whether\n",
    "it can be avoided.\n",
    "\n",
    "## Recursion and memoization: binomial coefficients\n",
    "\n",
    "Altenkirch and Triguero derive a recurrence for the number of ways to choose $m$ balls out of $n$. We\n",
    "look at the ball with the largest number: either we take it (it remains to choose $m-1$ out of\n",
    "$n-1$), or we do not (it remains to choose $m$ out of $n-1$). Hence\n",
    "\n",
    "$$\n",
    "\\binom{n}{m}=\\binom{n-1}{m}+\\binom{n-1}{m-1},\\qquad \\binom{n}{0}=1,\\qquad\n",
    "\\binom{0}{m}=0\\ \\text{for}\\ m>0.\n",
    "$$\n",
    "\n",
    "The program follows directly from the formula:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "215656cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def dwumian(n, m):\n",
    "    if m == 0:\n",
    "        return 1\n",
    "    if n == 0:\n",
    "        return 0\n",
    "    return dwumian(n - 1, m) + dwumian(n - 1, m - 1)\n",
    "\n",
    "\n",
    "print(\"dwumian(24, 6) =\", dwumian(24, 6),\n",
    "      \"  math.comb(24, 6) =\", math.comb(24, 6))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ee2fbcb",
   "metadata": {},
   "source": [
    "The program is correct, but it computes the same values many times. For example, it computes\n",
    "$\\binom{n-2}{m-1}$ twice: once via $\\binom{n-1}{m}$, and a second time via $\\binom{n-1}{m-1}$. How\n",
    "many calls does it make for various arguments? The number of calls $L(n,m)$ satisfies the same\n",
    "recurrence as the binomial coefficient itself, only plus one for the current call. We will compute\n",
    "it with memoization (more on that in a moment), because otherwise counting the calls would take as\n",
    "long as making them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3951414e",
   "metadata": {},
   "outputs": [],
   "source": [
    "@cache\n",
    "def wywolania(n, m):\n",
    "    \"\"\"Liczba wywołań funkcji dwumian(n, m), łącznie z pierwszym.\"\"\"\n",
    "    if m == 0 or n == 0:\n",
    "        return 1\n",
    "    return 1 + wywolania(n - 1, m) + wywolania(n - 1, m - 1)\n",
    "\n",
    "\n",
    "t_wywolania = zmierz(dwumian, 24, 6) / wywolania(24, 6)\n",
    "for n_, m_ in ((24, 6), (30, 6), (49, 6)):\n",
    "    L = wywolania(n_, m_)\n",
    "    print(f\"C({n_},{m_}) = {math.comb(n_, m_):>10}:  wywołań {L:>11},\",\n",
    "          f\"szacowany czas {czas(L * t_wywolania)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4daeb92",
   "metadata": {},
   "source": [
    "The number of calls grows together with the result: every leaf of the recursion tree returns $0$ or\n",
    "$1$, so there are at least $\\binom{n}{m}$ leaves. The time estimate is the number of calls multiplied\n",
    "by the average time of one call, measured for $\\binom{24}{6}$. For $\\binom{49}{6}$, that is, the\n",
    "number of possible outcomes of a Lotto draw, it takes tens of millions of calls and a time on the\n",
    "order of a second. In the book by Altenkirch and Triguero, published in 2020, the same computation\n",
    "took “a few seconds.”\n",
    "\n",
    "The remedy is “lazy” in the best sense: we remember the values already computed. The decorator\n",
    "`functools.cache` attaches a dictionary (arguments → result) to the function. Each pair $(n,m)$ is\n",
    "then computed once, so there are $O(nm)$ calls instead of exponentially many. This is the same\n",
    "decorator that sped up the computation of Fibonacci numbers in Lecture 1\n",
    "({doc}`§1.2 <../wyklady/w01_2_python_matematyka>`), there in its older form\n",
    "`lru_cache(maxsize=None)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "459663fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "@cache\n",
    "def dwumian_pamiec(n, m):\n",
    "    if m == 0:\n",
    "        return 1\n",
    "    if n == 0:\n",
    "        return 0\n",
    "    return dwumian_pamiec(n - 1, m) + dwumian_pamiec(n - 1, m - 1)\n",
    "\n",
    "\n",
    "def dwumian_od_nowa(n, m):\n",
    "    dwumian_pamiec.cache_clear()       # mierzymy liczenie, a nie odczyt\n",
    "    return dwumian_pamiec(n, m)\n",
    "\n",
    "\n",
    "def dwumian_silnie(n, m):\n",
    "    return math.factorial(n) // (math.factorial(m) * math.factorial(n - m))\n",
    "\n",
    "\n",
    "czasy_dwumian = porownaj({\"rekurencja\": dwumian,\n",
    "                          \"rekurencja + @cache\": dwumian_od_nowa,\n",
    "                          \"silnie\": dwumian_silnie,\n",
    "                          \"math.comb\": math.comb}, 24, 6)\n",
    "print(\"C(49, 6) z pamięcią:\", dwumian_od_nowa(49, 6))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b18b7de5",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "szacunek_49 = wywolania(49, 6) * t_wywolania\n",
    "upewnij(10**7 < wywolania(49, 6) < 10**8 and 0.2 < szacunek_49 < 5,\n",
    "        \"C(49, 6) wymaga dziesiątek milionów wywołań i czasu rzędu sekundy\")\n",
    "upewnij(czasy_dwumian[\"rekurencja\"]\n",
    "        > 100 * czasy_dwumian[\"rekurencja + @cache\"],\n",
    "        \"zapamiętywanie przyspiesza rekurencję ponad sto razy\")\n",
    "upewnij(zmierz(dwumian_od_nowa, 49, 6) < 1e-3,\n",
    "        \"C(49, 6) z pamięcią liczy się w ułamku milisekundy\")\n",
    "upewnij(czasy_dwumian[\"rekurencja + @cache\"] > czasy_dwumian[\"math.comb\"],\n",
    "        \"math.comb jest szybsze od rekurencji z pamięcią\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d29c73e",
   "metadata": {},
   "source": [
    "The single line `@cache` speeds up the recursion more than a hundred times, and $\\binom{49}{6}$ is\n",
    "now computed in a fraction of a millisecond. The fastest, however, is the ready-made function\n",
    "`math.comb` from the standard library. It is written in C and uses product formulas rather than\n",
    "Pascal’s recurrence. This is another rung of laziness: before we write a function, we check whether\n",
    "it is already in a library ({doc}`part 4 <p4_biblioteka>`).\n",
    "\n",
    "```{admonition} When memoization helps\n",
    ":class: note\n",
    "A cache helps when the function is **pure**: its result depends only on its arguments, and a call\n",
    "changes nothing outside it. The function `dwumian` is pure. A function that reads a global variable\n",
    "or draws random numbers is not, and its remembered result may be out of date. The arguments must\n",
    "also be hashable (numbers, strings, tuples — but not lists). The memory used grows with the number\n",
    "of distinct arguments, and `lru_cache(maxsize=...)` bounds it by evicting the least recently used\n",
    "entries.\n",
    "```\n",
    "\n",
    "## Memoization in a loop: Collatz steps\n",
    "\n",
    "In Lecture 1 we computed Collatz trajectories: $n\\mapsto n/2$ for even numbers, $n\\mapsto3n+1$ for\n",
    "odd ones, until we reach $1$. In Lab 8 we plot the number of steps for all $n\\le3000$. The\n",
    "trajectories of different numbers merge quickly; for example, the trajectory of $6$ passes through\n",
    "$3$. The number of steps for $3$ is then already known and does not have to be computed a second\n",
    "time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4230765",
   "metadata": {},
   "outputs": [],
   "source": [
    "def kroki(n):\n",
    "    k = 0\n",
    "    while n != 1:\n",
    "        n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "        k += 1\n",
    "    return k\n",
    "\n",
    "\n",
    "def kroki_wszystkie(N):\n",
    "    return [kroki(n) for n in range(1, N + 1)]\n",
    "\n",
    "\n",
    "def kroki_slownik(N):\n",
    "    \"\"\"To samo z pamięcią: słownik liczba → liczba kroków.\"\"\"\n",
    "    znane = {1: 0}\n",
    "    for start in range(2, N + 1):\n",
    "        droga, n = [], start\n",
    "        while n not in znane:              # idziemy do pierwszej znanej liczby\n",
    "            droga.append(n)\n",
    "            n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "        k = znane[n]\n",
    "        for m in reversed(droga):          # i uzupełniamy drogę od końca\n",
    "            k += 1\n",
    "            znane[m] = k\n",
    "    return [znane[n] for n in range(1, N + 1)]\n",
    "\n",
    "\n",
    "@cache\n",
    "def kroki_pamiec(n):\n",
    "    if n == 1:\n",
    "        return 0\n",
    "    return 1 + kroki_pamiec(n // 2 if n % 2 == 0 else 3 * n + 1)\n",
    "\n",
    "\n",
    "def kroki_cache(N):\n",
    "    kroki_pamiec.cache_clear()\n",
    "    return [kroki_pamiec(n) for n in range(1, N + 1)]\n",
    "\n",
    "\n",
    "N = 10**5\n",
    "czasy_collatz = porownaj({\"każda liczba osobno\": kroki_wszystkie,\n",
    "                          \"słownik znanych wyników\": kroki_slownik,\n",
    "                          \"@cache\": kroki_cache}, N)\n",
    "wynik = kroki_cache(N)\n",
    "rekord = max(range(N), key=wynik.__getitem__)\n",
    "print(f\"najwięcej kroków dla n ≤ {N}: {wynik[rekord]} (n = {rekord + 1})\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5686996f",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_collatz[\"każda liczba osobno\"] > 4 * czasy_collatz[\"@cache\"],\n",
    "        \"pamięć skraca liczenie kroków Collatza wielokrotnie\")\n",
    "upewnij(100 <= wynik[rekord] < 1000, \"rekordowa liczba kroków to kilkaset\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d8bc1ec",
   "metadata": {},
   "source": [
    "Memoization makes the computation many times faster. The version with a dictionary shows what happens\n",
    "inside: we walk along the trajectory to the first number whose number of steps is known, and then\n",
    "fill in the path backward from its end. The version with `@cache` does the same with a single\n",
    "decorator, but recursively. The recursion depth here equals the length of the longest unknown path,\n",
    "and this does not exceed the record number of steps (a few hundred). That is less than Python’s\n",
    "recursion limit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76fc4e9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "print(\"limit rekurencji:\", sys.getrecursionlimit())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6b0246e",
   "metadata": {},
   "source": [
    "For longer paths, the version with a dictionary, which uses no recursion, would be safer.\n",
    "\n",
    "## A better parametrization: Pythagorean triples\n",
    "\n",
    "In Lecture 1 we found the primitive Pythagorean triples with $c<30$ by a triple loop over $a<b<c$.\n",
    "Such a loop checks about $c^3/6$ triples. Euclid gives a parametrization: for coprime $m>k\\ge1$ of\n",
    "opposite parity, the triple\n",
    "\n",
    "$$\n",
    "a=m^2-k^2,\\qquad b=2mk,\\qquad c=m^2+k^2\n",
    "$$\n",
    "\n",
    "is a primitive Pythagorean triple, and every primitive triple arises in this way exactly once (up to\n",
    "swapping $a$ and $b$). SymPy will check the identity $(m^2-k^2)^2+(2mk)^2=(m^2+k^2)^2$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f4899f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "m, k = sp.symbols(\"m k\")\n",
    "print(sp.expand((m**2 - k**2)**2 + (2*m*k)**2 - (m**2 + k**2)**2) == 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26fee2d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def trojki_petle(C):\n",
    "    return {(a, b, c)\n",
    "            for c in range(1, C) for b in range(1, c) for a in range(1, b)\n",
    "            if a*a + b*b == c*c and math.gcd(a, b) == 1}\n",
    "\n",
    "\n",
    "def trojki_euklides(C):\n",
    "    wynik = set()\n",
    "    m = 2\n",
    "    while m * m + 1 < C:\n",
    "        for k in range(1, m):\n",
    "            if (m - k) % 2 == 1 and math.gcd(m, k) == 1 and m*m + k*k < C:\n",
    "                a, b = m*m - k*k, 2*m*k\n",
    "                wynik.add((min(a, b), max(a, b), m*m + k*k))\n",
    "        m += 1\n",
    "    return wynik\n",
    "\n",
    "\n",
    "czasy_trojki = porownaj({\"trzy pętle\": trojki_petle,\n",
    "                         \"parametryzacja Euklidesa\": trojki_euklides}, 150)\n",
    "print(\"trójek z c < 150:\", len(trojki_euklides(150)),\n",
    "      \"| z c < 10^6:\", len(trojki_euklides(10**6)))\n",
    "print(f\"potrójna pętla dla c < 10^6 sprawdziłaby\",\n",
    "      f\"{math.comb(10**6 - 1, 3):.2e} trójek\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1cca88f8",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_trojki[\"trzy pętle\"]\n",
    "        > 100 * czasy_trojki[\"parametryzacja Euklidesa\"],\n",
    "        \"parametryzacja jest ponad sto razy szybsza od trzech pętli\")\n",
    "upewnij(zmierz(trojki_euklides, 10**6) < 1,\n",
    "        \"parametryzacja dla c < 10^6 trwa ułamek sekundy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a0ad237",
   "metadata": {},
   "source": [
    "Both methods give the same set (`porownaj` checks this), but the parametrization is more than\n",
    "a hundred times faster already for $c<150$. For $c<10^6$ the triple loop would have to check about\n",
    "$1.7\\cdot10^{17}$ triples, which cannot be done. The parametrization enumerates all the triples in\n",
    "a fraction of a second, because it goes through only the pairs $(m,k)$ with $m^2<c$. A mathematical\n",
    "theorem has turned a search into an enumeration.\n",
    "\n",
    "## A smarter search: sudoku\n",
    "\n",
    "Altenkirch and Triguero solve sudoku by *backtracking*: they write the first digit allowed by the\n",
    "rules into the first empty cell and move on. When some cell has no allowed digit, they go back and\n",
    "try the next digit in an earlier cell. Let us write the same program and count the attempts, that\n",
    "is, the digits written into cells."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b6b8ef3",
   "metadata": {},
   "outputs": [],
   "source": [
    "ZAGADKI = {                    # wiersze planszy, 0 oznacza puste pole\n",
    "    \"łatwa\": (\"530070000\" \"600195000\" \"098000060\"\n",
    "              \"800060003\" \"400803001\" \"700020006\"\n",
    "              \"060000280\" \"000419005\" \"000080079\"),\n",
    "    \"trudna\": (\"800000000\" \"003600000\" \"070090000\"\n",
    "               \"050007000\" \"000045700\" \"000100030\"\n",
    "               \"001000068\" \"008500010\" \"090000400\"),\n",
    "}\n",
    "\n",
    "\n",
    "def plansza(napis):\n",
    "    return [[int(napis[9 * w + k]) for k in range(9)] for w in range(9)]\n",
    "\n",
    "\n",
    "def napis(P):\n",
    "    return \"\".join(str(c) for wiersz in P for c in wiersz)\n",
    "\n",
    "\n",
    "def mozna_wpisac(P, w, k, c):\n",
    "    if c in P[w] or any(P[i][k] == c for i in range(9)):\n",
    "        return False\n",
    "    w0, k0 = 3 * (w // 3), 3 * (k // 3)\n",
    "    return all(P[w0 + i][k0 + j] != c for i in range(3) for j in range(3))\n",
    "\n",
    "\n",
    "def nawroty(zagadka):\n",
    "    \"\"\"Pierwsze puste pole, cyfry po kolei. Zwraca (rozwiązanie, próby).\"\"\"\n",
    "    P, proby = plansza(zagadka), 0\n",
    "\n",
    "    def krok():\n",
    "        nonlocal proby\n",
    "        for w in range(9):\n",
    "            for k in range(9):\n",
    "                if P[w][k] == 0:\n",
    "                    for c in range(1, 10):\n",
    "                        if mozna_wpisac(P, w, k, c):\n",
    "                            proby += 1\n",
    "                            P[w][k] = c\n",
    "                            if krok():\n",
    "                                return True\n",
    "                            P[w][k] = 0\n",
    "                    return False           # żadna cyfra nie pasuje: cofamy się\n",
    "        return True                        # brak pustych pól: rozwiązane\n",
    "\n",
    "    krok()\n",
    "    return napis(P), proby"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce3d78b5",
   "metadata": {},
   "source": [
    "The second version changes two things. For each row, column, and box it keeps the set of digits\n",
    "already used, so checking a digit is a lookup in a set instead of a scan of 27 cells. More\n",
    "importantly, it starts with the cell that has the **fewest** allowed digits. It fills in a cell with\n",
    "only one possibility at once, without guessing, and when some cell has none, it backtracks\n",
    "immediately."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec872836",
   "metadata": {},
   "outputs": [],
   "source": [
    "def nawroty_najmniej_mozliwosci(zagadka):\n",
    "    \"\"\"Najpierw pole o najmniejszej liczbie kandydatów.\n",
    "\n",
    "    Zwraca (rozwiązanie, liczba prób).\n",
    "    \"\"\"\n",
    "    P, proby = plansza(zagadka), 0\n",
    "    wiersze = [set(P[w]) for w in range(9)]\n",
    "    kolumny = [{P[w][k] for w in range(9)} for k in range(9)]\n",
    "    kwadraty = [{P[w][k] for w in range(9) for k in range(9)\n",
    "                 if 3 * (w // 3) + k // 3 == b} for b in range(9)]\n",
    "    puste = [(w, k) for w in range(9) for k in range(9) if P[w][k] == 0]\n",
    "    cyfry = set(range(1, 10))\n",
    "\n",
    "    def kandydaci(w, k):\n",
    "        kwadrat = kwadraty[3 * (w // 3) + k // 3]\n",
    "        return cyfry - wiersze[w] - kolumny[k] - kwadrat\n",
    "\n",
    "    def krok():\n",
    "        nonlocal proby\n",
    "        if not puste:\n",
    "            return True\n",
    "        i = min(range(len(puste)), key=lambda i: len(kandydaci(*puste[i])))\n",
    "        w, k = puste.pop(i)\n",
    "        grupy = (wiersze[w], kolumny[k], kwadraty[3 * (w // 3) + k // 3])\n",
    "        for c in kandydaci(w, k):\n",
    "            proby += 1\n",
    "            P[w][k] = c\n",
    "            for g in grupy:\n",
    "                g.add(c)\n",
    "            if krok():\n",
    "                return True\n",
    "            for g in grupy:\n",
    "                g.remove(c)\n",
    "        P[w][k] = 0\n",
    "        puste.insert(i, (w, k))\n",
    "        return False\n",
    "\n",
    "    krok()\n",
    "    return napis(P), proby\n",
    "\n",
    "\n",
    "def poprawne(rozwiazanie, zagadka):\n",
    "    \"\"\"Kontroler: cyfry 1–9 w każdym wierszu, kolumnie i kwadracie.\n",
    "\n",
    "    Pola dane w zagadce muszą zostać bez zmian.\n",
    "    \"\"\"\n",
    "    P = plansza(rozwiazanie)\n",
    "    wiersze = [P[w] for w in range(9)]\n",
    "    kolumny = [[P[w][k] for w in range(9)] for k in range(9)]\n",
    "    kwadraty = [[P[w][k] for w in range(9) for k in range(9)\n",
    "                 if 3 * (w // 3) + k // 3 == b] for b in range(9)]\n",
    "    grupy = wiersze + kolumny + kwadraty\n",
    "    return (all(sorted(g) == list(range(1, 10)) for g in grupy)\n",
    "            and all(z in \"0\" + r for z, r in zip(zagadka, rozwiazanie)))\n",
    "\n",
    "\n",
    "czasy_sudoku = {}\n",
    "for nazwa, zagadka in ZAGADKI.items():\n",
    "    for metoda in (nawroty, nawroty_najmniej_mozliwosci):\n",
    "        rozwiazanie, proby = metoda(zagadka)\n",
    "        assert poprawne(rozwiazanie, zagadka)\n",
    "        czasy_sudoku[nazwa, metoda.__name__] = t = zmierz(metoda, zagadka)\n",
    "        print(f\"{nazwa:7} {metoda.__name__:28} prób: {proby:7}\",\n",
    "              f\"  czas: {czas(t)}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1cac5180",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "proby_trudna = {m.__name__: m(ZAGADKI[\"trudna\"])[1]\n",
    "                for m in (nawroty, nawroty_najmniej_mozliwosci)}\n",
    "upewnij(proby_trudna[\"nawroty\"] > 10**5\n",
    "        and proby_trudna[\"nawroty\"]\n",
    "        > 100 * proby_trudna[\"nawroty_najmniej_mozliwosci\"],\n",
    "        \"zwykłe nawroty: ponad sto tysięcy prób, wersja z wyborem pola: \"\n",
    "        \"ponad sto razy mniej\")\n",
    "upewnij(20 < czasy_sudoku[\"trudna\", \"nawroty\"]\n",
    "        / czasy_sudoku[\"trudna\", \"nawroty_najmniej_mozliwosci\"] < 100,\n",
    "        \"przy trudnej zagadce wybór pola z najmniejszą liczbą możliwości daje \"\n",
    "        \"kilkudziesięciokrotne przyspieszenie\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8deacf95",
   "metadata": {},
   "source": [
    "Both versions solve the easy puzzle (the same one that Altenkirch and Triguero solve) quickly. For\n",
    "the hard puzzle, plain backtracking needs more than a hundred thousand attempts, while the version\n",
    "that starts with the cell with the fewest candidates needs over a hundred times fewer and runs a few\n",
    "dozen times faster. The checker `poprawne` verifies each solution independently of the method that\n",
    "found it. This is the same division of roles as throughout the course: the search may be clever or\n",
    "not, but the result is checked by a simple program.\n",
    "\n",
    "The order in which we search through the possibilities determines the running time far more than\n",
    "the speed of a single step. We will see the same lesson in Lectures 7 and 8. The geometry engine\n",
    "(Lecture 7) and proof search in Peano Lab (Lecture 8) also search huge trees. There, a language\n",
    "model is in essence a hint about which branch to start with. P. Norvig writes more about sudoku in\n",
    "this spirit in his essay *Solving Every Sudoku Puzzle*, where he combines constraint propagation\n",
    "with choosing the cell that has the fewest candidates.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* First we ask **whether we need to compute at all**: a formula for a sum of powers replaces a loop,\n",
    "  Euclid’s parametrization replaces a search.\n",
    "* A recursion that computes the same values many times needs a **cache**: the single line\n",
    "  `@functools.cache` turns exponential time into polynomial time. We memoize only pure functions.\n",
    "* In a search, a **good order** gives the most: the most constrained decisions first.\n",
    "* The result of a clever algorithm is verified by a **simple checker** (`poprawne`, the comparison of\n",
    "  variants in `porownaj`).\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Write `fib(n)` without memoization and with `@cache`. Measure both variants for\n",
    "   $n=20, 25, 30$. By what factor does the time of the version without memoization grow when $n$\n",
    "   grows by $5$? Compare with $\\varphi^5$, where $\\varphi=(1+\\sqrt5)/2$.\n",
    "2. ★★ Prove that the function `dwumian(n, m)` makes exactly\n",
    "   $L(n,m)=2\\sum_{j=0}^{m}\\binom{n}{j}-1$ calls. Hint: the function $(L+1)/2$ satisfies Pascal’s\n",
    "   recurrence. Check the formula with the function `wywolania` for a few pairs $(n,m)$.\n",
    "3. ★★ Count the primitive Pythagorean triples with $c<N$ for $N=10^3,10^4,10^5,10^6$ and compare\n",
    "   with $N/(2\\pi)$.\n",
    "4. ★★ Add to `nawroty_najmniej_mozliwosci` a counter of the cells filled in “without guessing” (with\n",
    "   a single candidate). What fraction of all attempts is this for each of the two puzzles?"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
