{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d8d30d50",
   "metadata": {},
   "source": [
    "# Part 3. Lazy evaluation: generators and iterators\n",
    "\n",
    "In programming, the word “laziness” has a second, technical meaning. **Lazy evaluation** means\n",
    "that a value is computed only when someone needs it, not in advance. In Python, `range` objects\n",
    "and iterators are lazy: `map`, `filter`, `zip`, the functions of the `itertools` module, and above all\n",
    "generators, that is, functions with a `yield` statement and generator expressions. Laziness brings\n",
    "three benefits. A computation can finish earlier, there is no need to store all the values at\n",
    "once, and one can work with infinite sequences. It also has two drawbacks: a generator yields each\n",
    "value only once, and yielding values one at a time costs some time. The examples with the Collatz\n",
    "sequence and the sieve of Eratosthenes draw on the chapter on functional programming in the book\n",
    "by T. Altenkirch and I. Triguero, *Conceptual Programming with Python* (2020)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fba7184d",
   "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": "a4fd8de2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import itertools\n",
    "import math\n",
    "from itertools import count, islice\n",
    "\n",
    "srodowisko(\"numpy\", \"sympy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "922a83e8",
   "metadata": {},
   "source": [
    "## The Collatz sequence as a generator\n",
    "\n",
    "In Lecture 1, the function `collatz` built a list of all the terms of a trajectory. The version\n",
    "with `yield` produces the terms one at a time. After each `yield`, the function is suspended and\n",
    "resumes only when someone asks for the next value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f6ce545",
   "metadata": {},
   "outputs": [],
   "source": [
    "def collatz_lista(n):\n",
    "    ciag = [n]\n",
    "    while n != 1:\n",
    "        n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "        ciag.append(n)\n",
    "    return ciag\n",
    "\n",
    "\n",
    "def collatz(n):\n",
    "    \"\"\"Kolejne wyrazy trajektorii Collatza od n do 1, leniwie, po jednym.\"\"\"\n",
    "    while n != 1:\n",
    "        yield n\n",
    "        n = n // 2 if n % 2 == 0 else 3 * n + 1\n",
    "    yield 1\n",
    "\n",
    "\n",
    "print(\"pierwsze wyrazy:\", list(islice(collatz(27), 12)))\n",
    "print(\"liczba kroków:\", sum(1 for _ in collatz(27)) - 1,\n",
    "      \" największy wyraz:\", max(collatz(27)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f17df1ce",
   "metadata": {},
   "source": [
    "Let us ask for the first term of the trajectory of $27$ that is greater than $1000$. The list has\n",
    "to be built in full before we can start searching it. The generator stops at the first matching\n",
    "term:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bd5fc20",
   "metadata": {},
   "outputs": [],
   "source": [
    "pozycja, wyraz = next((k, v) for k, v in enumerate(collatz(27)) if v > 1000)\n",
    "print(f\"pierwszy wyraz > 1000: {wyraz} (wyraz numer {pozycja})\")\n",
    "print(f\"lista policzyła {len(collatz_lista(27))} wyrazów,\",\n",
    "      f\"generator {pozycja + 1}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd2153ad",
   "metadata": {},
   "source": [
    "The function `next` takes one value from the generator, and `enumerate` attaches an index to each\n",
    "term. Both are lazy, so the whole pipeline computes exactly as many terms as the answer requires.\n",
    "\n",
    "## Short-circuit evaluation: `any`, `all`, `next`\n",
    "\n",
    "The functions `all` and `any` stop as soon as they know the answer: `all` at the first false\n",
    "value, `any` at the first true one. With a generator, they also save computing the remaining\n",
    "values. Not so with a list, because the list is complete before `all` receives its first element.\n",
    "Let us check this on a primality test by trial division, for a large even number:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5ce4e0c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def pierwsza(n):\n",
    "    return n > 1 and all(n % d for d in range(2, math.isqrt(n) + 1))\n",
    "\n",
    "\n",
    "def pierwsza_lista(n):\n",
    "    return n > 1 and all([n % d for d in range(2, math.isqrt(n) + 1)])\n",
    "\n",
    "\n",
    "czasy_spiecie = porownaj({\"all(lista)\": pierwsza_lista,\n",
    "                          \"all(generator)\": pierwsza}, 10**12 + 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c13e8e0",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_spiecie[\"all(lista)\"] > 1000 * czasy_spiecie[\"all(generator)\"],\n",
    "        \"generator w all jest ponad tysiąc razy szybszy od listy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f68d5db",
   "metadata": {},
   "source": [
    "The list version computes a million remainders, the generator version just one: the remainder of\n",
    "division by $2$ is $0$, and `all` immediately returns `False`. The difference reaches several\n",
    "orders of magnitude.\n",
    "\n",
    "Short-circuit evaluation comes in handy when searching for counterexamples. Euler noticed that\n",
    "the polynomial $n^2+n+41$ gives primes for many consecutive $n$. Does it do so for all of them?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0d2d273",
   "metadata": {},
   "outputs": [],
   "source": [
    "testy = 0\n",
    "\n",
    "\n",
    "def euler_pierwsza(n):\n",
    "    global testy\n",
    "    testy += 1\n",
    "    return pierwsza(n * n + n + 41)\n",
    "\n",
    "\n",
    "print(\"pierwsze dla n < 100:\", all(euler_pierwsza(n) for n in range(100)),\n",
    "      f\"(wykonano {testy} testów)\")\n",
    "n0 = next(n for n in count() if not pierwsza(n * n + n + 41))\n",
    "print(f\"pierwszy kontrprzykład: n = {n0},  n² + n + 41 = {n0*n0 + n0 + 41}\",\n",
    "      f\"= {math.isqrt(n0*n0 + n0 + 41)}²\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "189bccf4",
   "metadata": {},
   "source": [
    "The function `all` stopped at the first counterexample and performed only as many tests as were\n",
    "needed. To find the counterexample, we used the infinite counter `count()`. This works because\n",
    "`next` stops at the first matching $n$. For $n=40$ we have $n^2+n+41=40\\cdot41+41=41^2$, so the\n",
    "counterexample is also easy to see without a computer.\n",
    "\n",
    "## Memory: a generator does not store values\n",
    "\n",
    "A list comprehension creates all the values at once and keeps them in memory. A generator keeps\n",
    "only its current state in memory. Let us measure the peak memory usage while summing a million\n",
    "squares, using the `tracemalloc` module, which tracks the memory allocations made by Python."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1af7129b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import tracemalloc\n",
    "\n",
    "\n",
    "def szczyt_pamieci(f, *args):\n",
    "    \"\"\"Największa ilość pamięci przydzielonej podczas f(*args), w bajtach.\"\"\"\n",
    "    tracemalloc.start()\n",
    "    f(*args)\n",
    "    szczyt = tracemalloc.get_traced_memory()[1]\n",
    "    tracemalloc.stop()\n",
    "    return szczyt\n",
    "\n",
    "\n",
    "def kwadraty_lista(n):\n",
    "    return sum([k * k for k in range(n)])\n",
    "\n",
    "\n",
    "def kwadraty_generator(n):\n",
    "    return sum(k * k for k in range(n))\n",
    "\n",
    "\n",
    "def rozmiar(bajty):\n",
    "    for jednostka, skala in ((\"MiB\", 2**20), (\"KiB\", 2**10)):\n",
    "        if bajty >= skala:\n",
    "            return f\"{bajty / skala:.1f} {jednostka}\"\n",
    "    return f\"{bajty} B\"\n",
    "\n",
    "\n",
    "pamiec = {f.__name__: szczyt_pamieci(f, 10**6)\n",
    "          for f in (kwadraty_lista, kwadraty_generator)}\n",
    "for nazwa, bajty in pamiec.items():\n",
    "    print(f\"{nazwa:19} szczyt pamięci: {rozmiar(bajty)}\")\n",
    "czasy_pamiec = porownaj({\"lista\": kwadraty_lista,\n",
    "                         \"generator\": kwadraty_generator}, 10**6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f412b22",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(10 * 2**20 < pamiec[\"kwadraty_lista\"] < 100 * 2**20\n",
    "        and pamiec[\"kwadraty_generator\"] < 2**10,\n",
    "        \"lista zajmuje dziesiątki megabajtów, generator mniej niż kilobajt\")\n",
    "r = czasy_pamiec[\"lista\"] / czasy_pamiec[\"generator\"]\n",
    "upewnij(0.5 < r < 2, \"czasy listy i generatora są podobne\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce261216",
   "metadata": {},
   "source": [
    "The list takes up tens of megabytes: a million pointers and a million integer objects. The\n",
    "generator needs less than a kilobyte, regardless of $n$. The running times of the two versions are\n",
    "similar. The list sometimes wins slightly, because it does not have to suspend and resume a\n",
    "generator, but with large data this gain stops mattering once memory runs short.\n",
    "\n",
    "`range` is lazy, too. The object `range(10**12)` takes up a few dozen bytes, and checking whether\n",
    "a number belongs to it is a computation, not a scan:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53ffab83",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "r12 = range(10**12)\n",
    "print(\"rozmiar obiektu range(10**12):\", sys.getsizeof(r12), \"bajtów\")\n",
    "print(\"10**12 - 1 in range(10**12):\", 10**12 - 1 in r12,\n",
    "      \" czas:\", czas(zmierz(lambda: 10**12 - 1 in r12)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9798ff6c",
   "metadata": {},
   "source": [
    "## Infinite sequences: prime numbers\n",
    "\n",
    "Altenkirch and Triguero show how to write the sieve of Eratosthenes lazily. We take the sequence\n",
    "of natural numbers starting from $2$. Its first term $p$ is a prime, so we yield it, and we sieve\n",
    "the rest of the sequence, removing the multiples of $p$. The sequence of natural numbers is also\n",
    "written recursively: the number $n$, followed by the numbers from $n+1$ on. The statement\n",
    "`yield from` passes on all the values of another generator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1741cf2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def naturalne(n):\n",
    "    yield n\n",
    "    yield from naturalne(n + 1)\n",
    "\n",
    "\n",
    "def sito(liczby):\n",
    "    p = next(liczby)\n",
    "    yield p\n",
    "    yield from (k for k in sito(liczby) if k % p != 0)\n",
    "\n",
    "\n",
    "print(list(islice(sito(naturalne(2)), 15)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c593a985",
   "metadata": {},
   "source": [
    "The code is short and beautiful. But let us try to take more primes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "682173f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "def ile_przed_bledem(generator):\n",
    "    ile = ostatnia = 0\n",
    "    try:\n",
    "        for ostatnia in generator:\n",
    "            ile += 1\n",
    "    except RecursionError:\n",
    "        return ile, ostatnia\n",
    "\n",
    "\n",
    "for opis, liczby in ((\"naturalne(2)\", naturalne(2)), (\"count(2)\", count(2))):\n",
    "    ile, ostatnia = ile_przed_bledem(sito(liczby))\n",
    "    print(f\"sito({opis}): RecursionError po {ile} liczbach pierwszych\",\n",
    "          f\"(ostatnia {ostatnia})\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6607b9f0",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(all(20 <= ile_przed_bledem(sito(l))[0] <= 300\n",
    "            for l in (naturalne(2), count(2))),\n",
    "        \"leniwe sito kończy się błędem po kilkudziesięciu liczbach pierwszych\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d8ae206",
   "metadata": {},
   "source": [
    "The program fails with a `RecursionError` after only a few dozen primes. Every prime found adds a\n",
    "new layer of generators: a number on its way to the output passes through the filters of all the\n",
    "earlier primes, and each filter is another call on the stack. In Python, the stack has a limited\n",
    "depth. The recursive sequence `naturalne` adds layers of its own, so with `itertools.count` we get\n",
    "a little further, but not far.\n",
    "\n",
    "There is also a second, less visible problem. M. E. O'Neill (*The Genuine Sieve of Eratosthenes*,\n",
    "J. Funct. Programming 2009) observed that this is not the sieve of Eratosthenes at all. Here,\n",
    "every prime $q$ is divided by **all** the smaller primes. The sieve only crosses out multiples,\n",
    "and trial division checks divisors only up to $\\sqrt q$. Let us count the divisions made while\n",
    "finding the primes below $300$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc35496b",
   "metadata": {},
   "outputs": [],
   "source": [
    "dzielenia = 0\n",
    "\n",
    "\n",
    "def niepodzielna(k, p):\n",
    "    global dzielenia\n",
    "    dzielenia += 1\n",
    "    return k % p != 0\n",
    "\n",
    "\n",
    "def sito_liczace(liczby):\n",
    "    p = next(liczby)\n",
    "    yield p\n",
    "    yield from (k for k in sito_liczace(liczby) if niepodzielna(k, p))\n",
    "\n",
    "\n",
    "def dzielenia_testu(N):\n",
    "    \"\"\"Dzielenia w teście d = 2, 3, ..., √k dla wszystkich k < N.\"\"\"\n",
    "    ile = 0\n",
    "    for k in range(2, N):\n",
    "        for d in range(2, math.isqrt(k) + 1):\n",
    "            ile += 1\n",
    "            if k % d == 0:\n",
    "                break\n",
    "    return ile\n",
    "\n",
    "\n",
    "pierwsze_300 = list(itertools.takewhile(lambda p: p < 300,\n",
    "                                        sito_liczace(count(2))))\n",
    "dzielenia_sita, dzielenia_proby = dzielenia, dzielenia_testu(300)\n",
    "print(f\"liczb pierwszych < 300: {len(pierwsze_300)}\")\n",
    "print(f\"leniwe „sito”: {dzielenia_sita} dzieleń;\",\n",
    "      f\"dzielenie przez d ≤ √k: {dzielenia_proby} dzieleń\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8dde4f2",
   "metadata": {},
   "source": [
    "The lazy “sieve” performed many times more divisions than ordinary trial division, which for each\n",
    "number $k$ checks the divisors $2,3,\\dots$ until it finds the first divisor or reaches $\\sqrt k$.\n",
    "\n",
    "A genuine lazy sieve keeps a dictionary: for each upcoming composite number, it remembers the\n",
    "primes that will cross it out. A number that is not in the dictionary is prime. We then record\n",
    "that $p$ will first cross out $p^2$. A number found in the dictionary is composite. We then move\n",
    "each of its primes on to the next multiple of that prime. The generator is infinite and uses no\n",
    "recursion."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a39be9aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "def pierwsze():\n",
    "    \"\"\"Wszystkie liczby pierwsze po kolei: leniwe sito ze słownikiem.\"\"\"\n",
    "    skresli = {}           # liczba złożona → liczby pierwsze, które ją skreślą\n",
    "    for n in count(2):\n",
    "        if n not in skresli:\n",
    "            yield n\n",
    "            skresli[n * n] = [n]\n",
    "        else:\n",
    "            for p in skresli.pop(n):\n",
    "                skresli.setdefault(n + p, []).append(p)\n",
    "\n",
    "\n",
    "print(list(islice(pierwsze(), 15)), \"...\",\n",
    "      next(islice(pierwsze(), 9999, None)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70585ac5",
   "metadata": {},
   "source": [
    "The last number is the ten-thousandth prime. When an upper bound is known, the fastest option is\n",
    "the ordinary, “eager” sieve on a byte array. The slice assignment `jest[p*p::p]` crosses out all\n",
    "the multiples of $p$ in a single operation in C. Let us compare all the versions, first for the\n",
    "numbers below $300$, because the lazy “sieve” does not reach any further:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54660157",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sympy import primepi\n",
    "from sympy.ntheory.generate import Sieve\n",
    "\n",
    "\n",
    "def lp_leniwe_sito(N):\n",
    "    return list(itertools.takewhile(lambda p: p < N, sito(count(2))))\n",
    "\n",
    "\n",
    "def lp_dzielenie(N):\n",
    "    return [n for n in range(2, N) if pierwsza(n)]\n",
    "\n",
    "\n",
    "def lp_slownik(N):\n",
    "    return list(itertools.takewhile(lambda p: p < N, pierwsze()))\n",
    "\n",
    "\n",
    "def lp_tablica(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",
    "def lp_numpy(N):\n",
    "    jest = np.ones(N, dtype=bool)\n",
    "    jest[:2] = False\n",
    "    for p in range(2, math.isqrt(N - 1) + 1):\n",
    "        if jest[p]:\n",
    "            jest[p * p::p] = False\n",
    "    return np.flatnonzero(jest).tolist()\n",
    "\n",
    "\n",
    "def lp_sympy(N):\n",
    "    return list(Sieve().primerange(2, N))      # nowe sito, bez pamięci\n",
    "\n",
    "\n",
    "czasy_300 = porownaj({\"leniwe „sito” z książki\": lp_leniwe_sito,\n",
    "                      \"dzielenie do √n\": lp_dzielenie,\n",
    "                      \"słownik (leniwe)\": lp_slownik,\n",
    "                      \"tablica bajtów\": lp_tablica,\n",
    "                      \"NumPy\": lp_numpy, \"SymPy Sieve\": lp_sympy}, 300)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52bebc9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "czasy_mln = porownaj({\"słownik (leniwe)\": lp_slownik,\n",
    "                      \"tablica bajtów\": lp_tablica,\n",
    "                      \"NumPy\": lp_numpy, \"SymPy Sieve\": lp_sympy}, 10**6)\n",
    "print(\"liczb pierwszych < 10^6:\", len(lp_tablica(10**6)),\n",
    "      \"  sympy.primepi:\", primepi(10**6))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5ced19d",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_300[\"leniwe „sito” z książki\"]\n",
    "        > 3 * czasy_300[\"dzielenie do √n\"],\n",
    "        \"leniwe sito jest wolniejsze od zwykłego dzielenia\")\n",
    "upewnij(dzielenia_sita > 3 * dzielenia_proby,\n",
    "        \"leniwe sito wykonuje wielokrotnie więcej dzieleń niż test\")\n",
    "upewnij(czasy_mln[\"słownik (leniwe)\"] > 5 * czasy_mln[\"tablica bajtów\"],\n",
    "        \"sito słownikowe jest wielokrotnie wolniejsze od tablicy bajtów\")\n",
    "upewnij(min(czasy_mln, key=czasy_mln.get) == \"NumPy\", \"NumPy jest najszybszy\")\n",
    "upewnij(czasy_mln[\"SymPy Sieve\"] > czasy_mln[\"tablica bajtów\"],\n",
    "        \"SymPy jest wolniejszy od tablicy bajtów\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd918ea8",
   "metadata": {},
   "source": [
    "There are three conclusions. The elegant lazy “sieve” is the slowest, slower even than plain trial\n",
    "division, and it does not get far. The genuine lazy sieve with a dictionary is many times slower\n",
    "than the byte array, but it does not need to know an upper bound. That is the price of laziness,\n",
    "sometimes worth paying. The fastest is the NumPy version, which crosses out with slices in the\n",
    "same way, only without converting the array into a list of Python numbers along the way (more on\n",
    "NumPy in {doc}`part 5 <p5_numpy>`). A symbolic library need not be the fastest: here SymPy’s sieve\n",
    "loses to a few lines of code on a byte array. The global sieve `sympy.sieve`, on the other hand,\n",
    "remembers the numbers it has already sieved, so later queries about the same range are much\n",
    "faster. In the measurement, we create a new sieve (`Sieve()`) so as not to measure this.\n",
    "\n",
    "## Iterators are one-shot\n",
    "\n",
    "Laziness has its pitfall, already familiar from part 1. An exhausted iterator yields nothing and\n",
    "raises no error. A common mistake looks like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3dd2683",
   "metadata": {},
   "outputs": [],
   "source": [
    "wartosci = map(lambda k: k * k, range(1, 6))\n",
    "print(\"największa:\", max(wartosci))\n",
    "print(\"suma:\", sum(wartosci))           # iterator jest już pusty!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07781e7f",
   "metadata": {},
   "source": [
    "The function `max` went through the whole iterator, so `sum` received an empty sequence and\n",
    "returned $0$. If the values are needed more than once, we store them in a list (`list(map(...))`)\n",
    "or build the iterator anew. `range` objects and lists can be traversed many times. Generators,\n",
    "`map`, `filter`, `zip`, and the objects from `itertools` are one-shot.\n",
    "\n",
    "## Lazy pipelines\n",
    "\n",
    "Iterators can be chained into pipelines. Each stage takes from the previous one as many values as\n",
    "it needs. Here are two examples. The first finds the first ten primes of the form $n^2+1$, the\n",
    "second the smallest $n$ for which the harmonic sum $H_n=1+\\tfrac12+\\dots+\\tfrac1n$ exceeds $10$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "066ae253",
   "metadata": {},
   "outputs": [],
   "source": [
    "from itertools import accumulate\n",
    "\n",
    "print(list(islice((n * n + 1 for n in count(1) if pierwsza(n * n + 1)), 10)))\n",
    "sumy_czesciowe = accumulate(1 / k for k in count(1))      # H_1, H_2, ...\n",
    "n10 = next(n for n, h in enumerate(sumy_czesciowe, start=1) if h > 10)\n",
    "print(\"najmniejsze n z H_n > 10:\", n10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d5d83c3",
   "metadata": {},
   "source": [
    "The function `accumulate` yields the partial sums, and `enumerate(..., start=1)` numbers them. No\n",
    "stage knows how many values will be needed. The pipeline is stopped by `islice` or `next`. We\n",
    "computed the result for $H_n$ with `float` numbers, but $H_{n-1}$ and $H_n$ lie on either side of\n",
    "$10$ at a distance of order $10^{-5}$, which is many times larger than the rounding errors, so the\n",
    "result is certain. Let us check this exactly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5dd46ba4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from fractions import Fraction\n",
    "\n",
    "H = sum(Fraction(1, k) for k in range(1, n10))\n",
    "print(\"H_(n-1) < 10 < H_n:\", H < 10 < H + Fraction(1, n10))\n",
    "print(f\"10 - H_(n-1) ≈ {float(10 - H):.2e},\",\n",
    "      f\" H_n - 10 ≈ {float(H + Fraction(1, n10) - 10):.2e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cbe3a3af",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(all(1e-6 < float(d) < 1e-4\n",
    "            for d in (10 - H, H + Fraction(1, n10) - 10)),\n",
    "        \"H_(n-1) i H_n leżą po dwóch stronach 10 w odległości rzędu 10^-5\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98841ba0",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "* Generators and iterators compute values **on demand**. `any`, `all`, `next`, and `islice` stop\n",
    "  as soon as they know the answer, so with a generator they do not compute unnecessary values.\n",
    "* A generator **does not store** values: its memory usage does not depend on the length of the\n",
    "  sequence. `range` is lazy, too.\n",
    "* Laziness makes it possible to work with **infinite sequences** (`count`, generators with\n",
    "  `while True`), but deep recursion of generators ends in a `RecursionError`, and elegant code\n",
    "  does not guarantee a good algorithm.\n",
    "* Iterators are **one-shot**. Values needed more than once are stored in a list.\n",
    "* When an upper bound is known, an eager array (a sieve on a `bytearray`, NumPy) can be much\n",
    "  faster than a lazy generator.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Write a generator `fibonacci()` that yields all the Fibonacci numbers. Use it to find the\n",
    "   first Fibonacci number with $1000$ digits. What is its position in the sequence?\n",
    "2. ★ Show that for every $n$ the number $n^2+n+41$ is not divisible by $2,3,5,\\dots,37$. Hint:\n",
    "   check the residues modulo each of these primes for $n=0,1,\\dots,p-1$.\n",
    "3. ★★ Rewrite `sito` so that it takes a list of the primes found so far and checks only the\n",
    "   divisors $p\\le\\sqrt k$. Measure whether this helps, and explain whether it is now the sieve of\n",
    "   Eratosthenes.\n",
    "4. ★★ Measure the peak memory of `sorted(k * k % 1000 for k in range(10**6))`. Does `sorted` with\n",
    "   a generator save memory? Why?"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
