{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f96681ee",
   "metadata": {},
   "source": [
    "# Part 4. The standard library: built-in functions and data structures\n",
    "\n",
    "The simplest kind of laziness is not writing what has already been written. The built-in\n",
    "functions (`sum`, `min`, `max`, `sorted`, `any`, `all`) and the modules of the standard library\n",
    "(`math`, `itertools`, `collections`, `heapq`, `bisect`, `functools`) are written in C, tested, and\n",
    "handle edge cases that are easy to forget. Then there is the choice of data structure: the same\n",
    "operation on a list and on a set can differ in running time by three orders of magnitude. In this\n",
    "part we will see examples from Lectures 1, 2, and 8. We will also check two popular beliefs that\n",
    "measurement confirms only in part."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "322867e0",
   "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": "5d45453f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import bisect\n",
    "import heapq\n",
    "import itertools\n",
    "import math\n",
    "import random\n",
    "from collections import Counter, defaultdict\n",
    "from fractions import Fraction\n",
    "\n",
    "srodowisko()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f39cf08b",
   "metadata": {},
   "source": [
    "## Summation: a loop, `sum`, `math.fsum`\n",
    "\n",
    "In Lecture 1 ({doc}`§1.4 <../wyklady/w01_4_obliczenie_sprawdzenie_dowod>`) we saw that, since\n",
    "version 3.12, the function `sum` adds `float` numbers using compensated summation, and `math.fsum`\n",
    "gives the correctly rounded sum. Let us add up a million copies of the number `0.1` and compare the\n",
    "result with the exact sum in rational numbers. The value `Fraction(0.1)` is the exact value of the\n",
    "machine number `0.1`, which is slightly larger than $1/10$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a1066a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "dane = [0.1] * 10**6\n",
    "dokladnie = Fraction(0.1) * 10**6    # dokładna suma liczb maszynowych\n",
    "ulp = math.ulp(1e5)                   # odstęp liczb float w pobliżu 10^5\n",
    "\n",
    "\n",
    "def suma_petla(xs):\n",
    "    s = 0.0\n",
    "    for v in xs:\n",
    "        s += v\n",
    "    return s\n",
    "\n",
    "\n",
    "SUMY = {\"pętla\": suma_petla, \"sum\": sum, \"math.fsum\": math.fsum}\n",
    "for nazwa, f in SUMY.items():\n",
    "    w = f(dane)\n",
    "    blad = abs(Fraction(w) - dokladnie) / Fraction(ulp)\n",
    "    print(f\"{nazwa:10} {w!r:22} błąd: {float(blad):9.1f} ulp\")\n",
    "print(\"dokładna suma zaokrąglona do float:\", float(dokladnie))\n",
    "czasy_suma = porownaj(SUMY, dane, zgodne=lambda a, b: True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dfa2f1d5",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(sum(dane) == math.fsum(dane) == float(dokladnie) != suma_petla(dane),\n",
    "        \"sum i fsum dają tu sumę poprawnie zaokrągloną, a pętla nie\")\n",
    "blad_petli = abs(Fraction(suma_petla(dane)) - dokladnie) / Fraction(ulp)\n",
    "upewnij(10**4 < blad_petli < 10**5\n",
    "        and 1e-6 < abs(suma_petla(dane) - 1e5) < 1e-5,\n",
    "        \"pętla myli się o kilkadziesiąt tysięcy ulp, w szóstej cyfrze\")\n",
    "upewnij(czasy_suma[\"pętla\"]\n",
    "        > 1.5 * max(czasy_suma[\"sum\"], czasy_suma[\"math.fsum\"]),\n",
    "        \"sum i fsum są szybsze od pętli\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "058e9e67",
   "metadata": {},
   "source": [
    "The loop adds from left to right and is off by tens of thousands of ulps, that is, in the sixth\n",
    "digit after the decimal point. The functions `sum` and `math.fsum` return the correctly rounded sum\n",
    "here, and they are faster than the loop as well. So the lazy choice is both faster and more\n",
    "accurate. For `float` data, `math.fsum` is a good default: it guarantees correct rounding, while\n",
    "`sum` only reduces the error. In the comparison, we allowed the results to differ\n",
    "(`zgodne=lambda a, b: True`), because the difference in the results was exactly what we wanted to\n",
    "show.\n",
    "\n",
    "## `in`: a list, a set, and binary search\n",
    "\n",
    "In Lecture 8 (§8.3) we check how many goals from the test set occur in the training data. For\n",
    "this, the code builds the set `stany = {p.stan for p in uczace}` and asks `p.stan in stany`. Why a\n",
    "set and not a list? The `in` operator on a list scans the elements one by one, so it costs $O(n)$.\n",
    "Sets and dictionaries are hash tables: they compute an element’s position in the table from its\n",
    "value, so a membership test takes constant time on average. In between lies binary search in a\n",
    "sorted list (the `bisect` module). It is the same bisection as in Lecture 5, only on integers, and\n",
    "the same strategy as in the number-guessing game from Altenkirch and Triguero’s book: guess the\n",
    "middle of the interval."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a560e2e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "los = random.Random(2026)\n",
    "elementy = [los.randrange(10**9) for _ in range(10**4)]\n",
    "pytania = [los.randrange(10**9) for _ in range(1000)] + elementy[:1000]\n",
    "zbior, posortowane = set(elementy), sorted(elementy)\n",
    "\n",
    "\n",
    "def w_liscie(q):\n",
    "    return q in elementy\n",
    "\n",
    "\n",
    "def w_zbiorze(q):\n",
    "    return q in zbior\n",
    "\n",
    "\n",
    "def binarnie(q):\n",
    "    i = bisect.bisect_left(posortowane, q)\n",
    "    return i < len(posortowane) and posortowane[i] == q\n",
    "\n",
    "\n",
    "czasy_in = porownaj({\n",
    "    \"lista: in\": lambda: sum(map(w_liscie, pytania)),\n",
    "    \"posortowana lista: bisect\": lambda: sum(map(binarnie, pytania)),\n",
    "    \"zbiór: in\": lambda: sum(map(w_zbiorze, pytania))})\n",
    "t_zbior = zmierz(set, elementy)\n",
    "t_pytanie = czasy_in[\"lista: in\"] / len(pytania)    # jedno pytanie do listy\n",
    "print(\"budowa zbioru:\", czas(t_zbior),\n",
    "      \"| sortowanie listy:\", czas(zmierz(sorted, elementy)))\n",
    "print(f\"budowa zbioru trwa tyle, co {t_zbior / t_pytanie:.0f} pytań do listy\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "397d2141",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_in[\"lista: in\"] > 100 * czasy_in[\"zbiór: in\"],\n",
    "        \"zbiór jest ponad sto razy szybszy od listy\")\n",
    "upewnij(czasy_in[\"lista: in\"] > czasy_in[\"posortowana lista: bisect\"]\n",
    "        > czasy_in[\"zbiór: in\"], \"bisect jest pośrodku\")\n",
    "upewnij(t_zbior / t_pytanie < 30,\n",
    "        \"budowa zbioru zwraca się po kilku–kilkunastu pytaniach\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "484f63a8",
   "metadata": {},
   "source": [
    "For ten thousand elements, the set answers two thousand queries more than a hundred times faster\n",
    "than the list, and binary search lies in between. Building the set is a one-time cost, roughly\n",
    "that of a few to a dozen or so queries to the list (the last line of the output), so it pays off\n",
    "quickly. A sorted list with `bisect` is useful when, besides the question “is it there?”, we also\n",
    "ask questions about order, for example, “how many elements are smaller than $q$?” A set cannot\n",
    "answer such questions.\n",
    "\n",
    "## Counting occurrences: `Counter`\n",
    "\n",
    "The frequency model from Lecture 8 counts how often each tactic appears in the data. The tool for\n",
    "counting occurrences is `collections.Counter`. Let us take an example from number theory. The last\n",
    "digits of primes greater than $5$ are $1$, $3$, $7$, or $9$. Do they occur equally often? And what\n",
    "do the last digits of **consecutive** primes look like?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9f6751a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def pierwsze_ponizej(N):\n",
    "    jest = bytearray([1]) * N\n",
    "    jest[0] = jest[1] = 0\n",
    "    for p in range(2, math.isqrt(N - 1) + 1):\n",
    "        if jest[p]:\n",
    "            jest[p * p::p] = bytes(len(range(p * p, N, p)))\n",
    "    return list(itertools.compress(range(N), jest))\n",
    "\n",
    "\n",
    "P = pierwsze_ponizej(10**6)\n",
    "cyfry = [p % 10 for p in P]\n",
    "print(\"ostatnie cyfry:\", \"  \".join(f\"{c}: {ile}\" for c, ile\n",
    "                                   in sorted(Counter(cyfry).items())))\n",
    "pary = Counter(zip(cyfry, cyfry[1:]))\n",
    "for a in (1, 3, 7, 9):\n",
    "    print(f\"po liczbie pierwszej z końcówką {a}:\",\n",
    "          \"  \".join(f\"{b}: {pary[a, b]:5}\" for b in (1, 3, 7, 9)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fca68c8",
   "metadata": {},
   "source": [
    "The individual digits are distributed almost evenly. Pairs of consecutive primes are not: after a\n",
    "prime ending in the digit $a$, the next prime ends in the same digit noticeably less often. This\n",
    "phenomenon was described by R. J. Lemke Oliver and K. Soundararajan (*Unexpected biases in the\n",
    "distribution of consecutive primes*, PNAS 2016). Now let us measure how much the counting itself\n",
    "costs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "930dcab9",
   "metadata": {},
   "outputs": [],
   "source": [
    "def licz_slownik(xs):\n",
    "    d = {}\n",
    "    for x in xs:\n",
    "        if x in d:\n",
    "            d[x] += 1\n",
    "        else:\n",
    "            d[x] = 1\n",
    "    return d\n",
    "\n",
    "\n",
    "def licz_defaultdict(xs):\n",
    "    d = defaultdict(int)\n",
    "    for x in xs:\n",
    "        d[x] += 1\n",
    "    return dict(d)\n",
    "\n",
    "\n",
    "pary_cyfr = list(zip(cyfry, cyfry[1:]))\n",
    "czasy_licz = porownaj({\"słownik i if\": licz_slownik,\n",
    "                       \"defaultdict\": licz_defaultdict,\n",
    "                       \"Counter\": lambda xs: dict(Counter(xs))}, pary_cyfr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d548f542",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_licz[\"Counter\"] < czasy_licz[\"słownik i if\"],\n",
    "        \"Counter jest szybszy od ręcznego liczenia\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39fe89cc",
   "metadata": {},
   "source": [
    "`Counter` is faster than a hand-written loop, and it is also shorter and has ready-made methods,\n",
    "for example `most_common`. The difference is not large here, because every version has to go\n",
    "through all the data. Here laziness pays off mainly in readability.\n",
    "\n",
    "## The $k$ smallest elements: `heapq`\n",
    "\n",
    "The $k$-nearest-neighbors method (kNN) from Lecture 8 looks for the $k$ most similar examples\n",
    "among all the training data. Sorting all the distances costs $O(n\\log n)$, but we only need the\n",
    "$k$ smallest. A heap from the `heapq` module finds them in time $O(n\\log k)$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7663e33e",
   "metadata": {},
   "outputs": [],
   "source": [
    "odleglosci = [los.random() for _ in range(10**5)]\n",
    "czasy_k = porownaj({\n",
    "    \"sorted(...)[:5]\": lambda: sorted(odleglosci)[:5],\n",
    "    \"heapq.nsmallest(5, ...)\": lambda: heapq.nsmallest(5, odleglosci),\n",
    "    \"min (gdy k = 1)\": lambda: [min(odleglosci)]},\n",
    "    zgodne=lambda a, b: a[0] == b[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4e422d8f",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_k[\"sorted(...)[:5]\"] > 5 * czasy_k[\"heapq.nsmallest(5, ...)\"],\n",
    "        \"heapq.nsmallest jest kilka razy szybszy od sortowania\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76817c80",
   "metadata": {},
   "source": [
    "The heap is many times faster than sorting the whole list. When only a single nearest neighbor is\n",
    "needed, a plain `min` is enough.\n",
    "\n",
    "## Building lists: `append` or `l = l + [x]`\n",
    "\n",
    "The first version of the function `collatz` in Altenkirch and Triguero’s book adds successive\n",
    "terms with the statement `l = l + [n]`. This looks innocent, but `l + [n]` creates a **new** list\n",
    "and copies all the existing elements into it. Building a list of length $n$ therefore costs\n",
    "$1+2+\\dots+n\\approx n^2/2$ copy operations. The method `append` adds the element in place, in\n",
    "constant time on average. A list reserves spare memory and enlarges it from time to time, in\n",
    "proportion to its length. Let us measure the running times for growing $n$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27ddda8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def doklejanie(n):\n",
    "    l = []\n",
    "    for k in range(n):\n",
    "        l = l + [k]\n",
    "    return l\n",
    "\n",
    "\n",
    "def dopisywanie(n):\n",
    "    l = []\n",
    "    for k in range(n):\n",
    "        l.append(k)\n",
    "    return l\n",
    "\n",
    "\n",
    "def skladana(n):\n",
    "    return [k for k in range(n)]\n",
    "\n",
    "\n",
    "rozmiary = [2500, 5000, 10000, 20000]\n",
    "serie = {\"l = l + [x]\": [zmierz(doklejanie, n) for n in rozmiary],\n",
    "         \"l.append(x)\": [zmierz(dopisywanie, n) for n in rozmiary],\n",
    "         \"lista składana\": [zmierz(skladana, n) for n in rozmiary]}\n",
    "assert doklejanie(1000) == dopisywanie(1000) == skladana(1000)\n",
    "print(f\"{'n':15}\", \"  \".join(f\"{n:>8}\" for n in rozmiary),\n",
    "      \"  czas(2n)/czas(n)\")\n",
    "for nazwa, t in serie.items():\n",
    "    print(f\"{nazwa:15}\", \"  \".join(czas(v).rjust(8) for v in t),\n",
    "          f\"  {(t[-1] / t[0]) ** (1 / 3):10.1f}\")\n",
    "wykres_skalowania(rozmiary, serie, \"Budowanie listy długości n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c804bb39",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "wzrost = {nazwa: (t[-1] / t[0]) ** (1 / 3) for nazwa, t in serie.items()}\n",
    "upewnij(wzrost[\"l = l + [x]\"] > 3 and wzrost[\"l.append(x)\"] < 2.6,\n",
    "        \"doklejanie rośnie kwadratowo, append liniowo\")\n",
    "upewnij(serie[\"l = l + [x]\"][-1] > 100 * serie[\"l.append(x)\"][-1],\n",
    "        \"doklejanie jest dla n = 20000 ponad sto razy wolniejsze\")\n",
    "upewnij(serie[\"lista składana\"][-1] < serie[\"l.append(x)\"][-1],\n",
    "        \"lista składana jest szybsza od append\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f68bdb2",
   "metadata": {},
   "source": [
    "When $n$ doubles, the running time of `l = l + [x]` roughly quadruples, while that of `append`\n",
    "doubles. On the log-log plot, this shows up as slopes $2$ and $1$. The list comprehension is even\n",
    "faster than `append`, because it does not call a method at every step. A quadratic cost hidden in\n",
    "innocent-looking code is the most common reason why programs run fine on small data and “hang” on\n",
    "large data.\n",
    "\n",
    "## Strings: `join` and `+=`\n",
    "\n",
    "For the same reason, textbooks recommend concatenating strings with `\"\".join(...)` rather than\n",
    "with `+=` in a loop. Strings in Python are immutable, so `s += t` ought to create a new string. Let\n",
    "us check how the running time grows when we add to the end, when we add to the beginning, and when\n",
    "we use `join`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "665f59ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "kawalki = [str(k) for k in range(4 * 10**5)]\n",
    "\n",
    "\n",
    "def na_koncu(xs):\n",
    "    s = \"\"\n",
    "    for x in xs:\n",
    "        s += x\n",
    "    return s\n",
    "\n",
    "\n",
    "def na_poczatku(xs):\n",
    "    s = \"\"\n",
    "    for x in reversed(xs):\n",
    "        s = x + s\n",
    "    return s\n",
    "\n",
    "\n",
    "czasy_napisy = porownaj({\"s += x (na końcu)\": na_koncu,\n",
    "                         \"s = x + s (na początku)\": na_poczatku,\n",
    "                         \"join\": \"\".join}, kawalki[:20000])\n",
    "for f in (na_koncu, na_poczatku):\n",
    "    t1, t4 = zmierz(f, kawalki[:20000]), zmierz(f, kawalki[:80000])\n",
    "    print(f\"{f.__name__}: czterokrotnie dłuższe dane, czas × {t4 / t1:.1f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ba5ce25",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "def wzrost(f):\n",
    "    return zmierz(f, kawalki[:80000]) / zmierz(f, kawalki[:20000])\n",
    "\n",
    "\n",
    "upewnij(wzrost(na_koncu) < 8, \"dopisywanie na końcu rośnie liniowo\")\n",
    "upewnij(wzrost(na_poczatku) > 8, \"dopisywanie na początku rośnie kwadratowo\")\n",
    "upewnij(czasy_napisy[\"join\"] < min(czasy_napisy[\"s += x (na końcu)\"],\n",
    "                                   czasy_napisy[\"s = x + s (na początku)\"]),\n",
    "        \"join jest najszybszy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2e9d15d",
   "metadata": {},
   "source": [
    "The result is more interesting than the textbook rule. Adding to the end scales linearly: CPython\n",
    "extends the string in place when nothing else holds a reference to it. This, however, is an\n",
    "implementation detail, not a guarantee of the language. The PEP 8 style guide explicitly advises\n",
    "against relying on it, because Python implementations without reference counting do not have it.\n",
    "Adding to the beginning scales quadratically, because each step copies the whole string. The\n",
    "function `join` is the fastest in all cases, because it first computes the length of the result\n",
    "and then copies each piece once. The conclusion: `join` is the safe choice, and measurement shows\n",
    "when the difference really matters.\n",
    "\n",
    "## Combinatorics: `itertools` and `math`\n",
    "\n",
    "The `itertools` module provides ready-made combinatorial iterators: `product`, `permutations`,\n",
    "`combinations`. In Lecture 6 (§6.3), this is how `product` enumerates the exponents of the\n",
    "monomials up to a given degree. Is a ready-made iterator faster than a loop? Let us compare three\n",
    "tasks: listing all the permutations of $8$ elements (our own recursion in the spirit of the chapter\n",
    "on combinatorics in Altenkirch and Triguero’s book, against `itertools.permutations`), listing the\n",
    "pairs $i<j$, and counting the triples $i<j<k$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2642a0ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "def permutacje(xs):\n",
    "    if len(xs) <= 1:\n",
    "        yield tuple(xs)\n",
    "        return\n",
    "    for i, x in enumerate(xs):\n",
    "        for reszta in permutacje(xs[:i] + xs[i + 1:]):\n",
    "            yield (x,) + reszta\n",
    "\n",
    "\n",
    "def pary_petle(n):\n",
    "    return [(i, j) for i in range(n) for j in range(i + 1, n)]\n",
    "\n",
    "\n",
    "def trojki_petle(n):\n",
    "    return sum(1 for i in range(n) for j in range(i + 1, n)\n",
    "               for k in range(j + 1, n))\n",
    "\n",
    "\n",
    "def trojki_combinations(n):\n",
    "    return sum(1 for _ in itertools.combinations(range(n), 3))\n",
    "\n",
    "\n",
    "czasy_perm = porownaj({\n",
    "    \"własna rekurencja\": lambda: list(permutacje(list(range(8)))),\n",
    "    \"itertools.permutations\": lambda: list(itertools.permutations(range(8)))})\n",
    "czasy_pary = porownaj({\n",
    "    \"dwie pętle\": lambda: pary_petle(1000),\n",
    "    \"itertools.combinations\":\n",
    "        lambda: list(itertools.combinations(range(1000), 2))})\n",
    "czasy_trojki = porownaj({\"trzy pętle\": trojki_petle,\n",
    "                         \"combinations\": trojki_combinations,\n",
    "                         \"math.comb(100, 3)\": lambda n: math.comb(n, 3)}, 100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d46378fb",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_perm[\"własna rekurencja\"]\n",
    "        > 5 * czasy_perm[\"itertools.permutations\"],\n",
    "        \"itertools.permutations jest wielokrotnie szybsze od rekurencji\")\n",
    "upewnij(1 / 3 < czasy_pary[\"dwie pętle\"]\n",
    "        / czasy_pary[\"itertools.combinations\"] < 3,\n",
    "        \"przy parach różnica jest niewielka\")\n",
    "upewnij(czasy_trojki[\"trzy pętle\"] / czasy_trojki[\"combinations\"] < 3,\n",
    "        \"przy liczeniu trójek combinations nie wygrywa wyraźnie\")\n",
    "upewnij(czasy_trojki[\"trzy pętle\"] > 1000 * czasy_trojki[\"math.comb(100, 3)\"],\n",
    "        \"wzór wygrywa o rzędy wielkości\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2118a637",
   "metadata": {},
   "source": [
    "For permutations, the ready-made iterator wins many times over, because our own recursion creates\n",
    "a multitude of intermediate lists and tuples. For pairs, the difference is small, and for counting\n",
    "triples the iterator does not win clearly, because `combinations` creates a tuple for each triple,\n",
    "which we do not use anyway. The gain from `itertools` is above all readability and laziness.\n",
    "Speed comes only when the iterator replaces a lot of work done in Python. Orders of magnitude come\n",
    "only from mathematics: the number of triples is given by the formula $\\binom{100}{3}$.\n",
    "\n",
    "## `math` and `pow`: exact functions on integers\n",
    "\n",
    "The `math` module has functions that compute exactly with integers of any size: `isqrt`, `gcd`,\n",
    "`lcm`, `comb`, `perm`, `factorial`, `prod`. Replacing them with computations on `float` numbers can\n",
    "be not only slower but also wrong. The integer part of a square root computed via `float` is wrong\n",
    "when the number has more than $15$–$16$ digits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b0bf08c",
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 10**16 - 1\n",
    "print(\"int(math.sqrt(n)) =\", int(math.sqrt(n)),\n",
    "      \"  math.isqrt(n) =\", math.isqrt(n))\n",
    "print(\"sprawdzenie isqrt:\", math.isqrt(n)**2 <= n < (math.isqrt(n) + 1)**2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa2e8b10",
   "metadata": {},
   "source": [
    "The number $10^{16}-1$ is not a machine number, so `float(n)` rounds it to $10^{16}$, whose square\n",
    "root is exactly $10^8$. Yet $(10^8)^2>n$, so the correct answer is $10^8-1$.\n",
    "\n",
    "With a third argument, the built-in function `pow` computes a power modulo $m$ by fast\n",
    "exponentiation. It performs about $\\log_2 b$ multiplications of numbers smaller than $m$. The\n",
    "expression `a**b % m` first computes the whole power, which for $b=10^6$ has hundreds of thousands\n",
    "of digits, and only then divides:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19fd8f61",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = 1_000_003\n",
    "print(\"3**(10**6) ma\", math.floor(10**6 * math.log10(3)) + 1, \"cyfr\")\n",
    "czasy_pow = porownaj({\"3**(10**6) % m\": lambda: 3**(10**6) % m,\n",
    "                      \"pow(3, 10**6, m)\": lambda: pow(3, 10**6, m)})\n",
    "print(\"odwrotność 3 modulo m: pow(3, -1, m) =\", pow(3, -1, m),\n",
    "      \"  sprawdzenie:\", 3 * pow(3, -1, m) % m)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9886d5b3",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_pow[\"3**(10**6) % m\"] > 10**4 * czasy_pow[\"pow(3, 10**6, m)\"],\n",
    "        \"pow z modułem jest ponad dziesięć tysięcy razy szybsze\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8c1ab3f",
   "metadata": {},
   "source": [
    "The three-argument `pow` is more than ten thousand times faster. The Fermat primality test and RSA\n",
    "cryptography rest on it. Since Python 3.8, `pow(a, -1, m)` also computes the inverse modulo $m$.\n",
    "\n",
    "We computed the number of digits of the power with the formula $\\lfloor b\\log_{10}3\\rfloor+1$, not\n",
    "with `len(str(...))`. Since version 3.11, Python refuses to convert an integer with more than\n",
    "$4300$ digits to a string and raises `ValueError`. This protects servers against attacks in which\n",
    "someone submits a gigantic number for conversion. Python stores integers in binary, and the\n",
    "conversion to decimal notation and back cannot be done in linear time, so for very long numbers it\n",
    "takes a long time. The limit can be changed with the function `sys.set_int_max_str_digits`.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* Before you write a loop, check the built-in functions and the standard library: `sum`,\n",
    "  `math.fsum`, `Counter`, `heapq`, `bisect`, `itertools`, `math`, `pow`. They are usually faster,\n",
    "  and often more accurate, too (`fsum`, `isqrt`).\n",
    "* The **data structure** determines the complexity: `in` on a list is $O(n)$, on a set or in a\n",
    "  dictionary $O(1)$ on average, and in a sorted list with `bisect` $O(\\log n)$.\n",
    "* Watch out for a **quadratic cost hidden in innocent-looking code**: `l = l + [x]` in a loop,\n",
    "  adding to the beginning of a string. Use `append`, list comprehensions, and `join`.\n",
    "* Popular rules are worth checking by measurement: `+=` at the end of a string is not quadratic in\n",
    "  CPython, and `itertools` is not always faster than a loop.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Write a function that computes the $\\gcd$ of many numbers in a loop, calling `math.gcd` with\n",
    "   two arguments, and compare it with `math.gcd(*liczby)` for $10^5$ random numbers.\n",
    "2. ★ Count the pairs of last digits of consecutive primes below $10^7$. Does the unevenness grow\n",
    "   or shrink?\n",
    "3. ★★ Implement the Fermat primality test: $n$ is “probably prime” if $a^{n-1}\\equiv1\\pmod n$ for\n",
    "   several random $a$. Compare the running times of `pow(a, n - 1, n)` and `a**(n - 1) % n` for\n",
    "   $n$ with $50$ digits. Find the smallest Carmichael number that fools this test.\n",
    "4. ★★ For a list of length $n$, compare `x in lista` with `x in set(lista)`, including the\n",
    "   construction of the set every time. After how many queries does building the set pay off?"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
