Part 4. The standard library: built-in functions and data structures#

The simplest kind of laziness is not writing what has already been written. The built-in functions (sum, min, max, sorted, any, all) and the modules of the standard library (math, itertools, collections, heapq, bisect, functools) are written in C, tested, and handle edge cases that are easy to forget. Then there is the choice of data structure: the same operation on a list and on a set can differ in running time by three orders of magnitude. In this part we will see examples from Lectures 1, 2, and 8. We will also check two popular beliefs that measurement confirms only in part.

Hide code cell source

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

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

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


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

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


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


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


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

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


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


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

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


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


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


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

srodowisko()
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11

Summation: a loop, sum, math.fsum#

In Lecture 1 (§1.4) we saw that, since version 3.12, the function sum adds float numbers using compensated summation, and math.fsum gives the correctly rounded sum. Let us add up a million copies of the number 0.1 and compare the result with the exact sum in rational numbers. The value Fraction(0.1) is the exact value of the machine number 0.1, which is slightly larger than \(1/10\).

dane = [0.1] * 10**6
dokladnie = Fraction(0.1) * 10**6    # dokładna suma liczb maszynowych
ulp = math.ulp(1e5)                   # odstęp liczb float w pobliżu 10^5


def suma_petla(xs):
    s = 0.0
    for v in xs:
        s += v
    return s


SUMY = {"pętla": suma_petla, "sum": sum, "math.fsum": math.fsum}
for nazwa, f in SUMY.items():
    w = f(dane)
    blad = abs(Fraction(w) - dokladnie) / Fraction(ulp)
    print(f"{nazwa:10} {w!r:22} błąd: {float(blad):9.1f} ulp")
print("dokładna suma zaokrąglona do float:", float(dokladnie))
czasy_suma = porownaj(SUMY, dane, zgodne=lambda a, b: True)
pętla      100000.00000133288     błąd:   91594.6 ulp
sum        100000.0               błąd:       0.4 ulp
math.fsum  100000.0               błąd:       0.4 ulp
dokładna suma zaokrąglona do float: 100000.0
wariant         czas  przyspieszenie
pętla        8.17 ms            1.0×
sum          3.58 ms            2.3×
math.fsum    3.59 ms            2.3×

The loop adds from left to right and is off by tens of thousands of ulps, that is, in the sixth digit after the decimal point. The functions sum and math.fsum return the correctly rounded sum here, and they are faster than the loop as well. So the lazy choice is both faster and more accurate. For float data, math.fsum is a good default: it guarantees correct rounding, while sum only reduces the error. In the comparison, we allowed the results to differ (zgodne=lambda a, b: True), because the difference in the results was exactly what we wanted to show.

Counting occurrences: Counter#

The frequency model from Lecture 8 counts how often each tactic appears in the data. The tool for counting occurrences is collections.Counter. Let us take an example from number theory. The last digits of primes greater than \(5\) are \(1\), \(3\), \(7\), or \(9\). Do they occur equally often? And what do the last digits of consecutive primes look like?

def pierwsze_ponizej(N):
    jest = bytearray([1]) * N
    jest[0] = jest[1] = 0
    for p in range(2, math.isqrt(N - 1) + 1):
        if jest[p]:
            jest[p * p::p] = bytes(len(range(p * p, N, p)))
    return list(itertools.compress(range(N), jest))


P = pierwsze_ponizej(10**6)
cyfry = [p % 10 for p in P]
print("ostatnie cyfry:", "  ".join(f"{c}: {ile}" for c, ile
                                   in sorted(Counter(cyfry).items())))
pary = Counter(zip(cyfry, cyfry[1:]))
for a in (1, 3, 7, 9):
    print(f"po liczbie pierwszej z końcówką {a}:",
          "  ".join(f"{b}: {pary[a, b]:5}" for b in (1, 3, 7, 9)))
ostatnie cyfry: 1: 19617  2: 1  3: 19665  5: 1  7: 19621  9: 19593
po liczbie pierwszej z końcówką 1: 1:  3213  3:  6299  7:  6550  9:  3555
po liczbie pierwszej z końcówką 3: 1:  4387  3:  2810  7:  5819  9:  6647
po liczbie pierwszej z końcówką 7: 1:  5069  3:  5443  7:  2873  9:  6236
po liczbie pierwszej z końcówką 9: 1:  6948  3:  5112  7:  4378  9:  3155

The individual digits are distributed almost evenly. Pairs of consecutive primes are not: after a prime ending in the digit \(a\), the next prime ends in the same digit noticeably less often. This phenomenon was described by R. J. Lemke Oliver and K. Soundararajan (Unexpected biases in the distribution of consecutive primes, PNAS 2016). Now let us measure how much the counting itself costs:

def licz_slownik(xs):
    d = {}
    for x in xs:
        if x in d:
            d[x] += 1
        else:
            d[x] = 1
    return d


def licz_defaultdict(xs):
    d = defaultdict(int)
    for x in xs:
        d[x] += 1
    return dict(d)


pary_cyfr = list(zip(cyfry, cyfry[1:]))
czasy_licz = porownaj({"słownik i if": licz_slownik,
                       "defaultdict": licz_defaultdict,
                       "Counter": lambda xs: dict(Counter(xs))}, pary_cyfr)
wariant            czas  przyspieszenie
słownik i if    4.37 ms            1.0×
defaultdict     3.50 ms            1.2×
Counter         2.40 ms            1.8×

Counter is faster than a hand-written loop, and it is also shorter and has ready-made methods, for example most_common. The difference is not large here, because every version has to go through all the data. Here laziness pays off mainly in readability.

The \(k\) smallest elements: heapq#

The \(k\)-nearest-neighbors method (kNN) from Lecture 8 looks for the \(k\) most similar examples among all the training data. Sorting all the distances costs \(O(n\log n)\), but we only need the \(k\) smallest. A heap from the heapq module finds them in time \(O(n\log k)\).

odleglosci = [los.random() for _ in range(10**5)]
czasy_k = porownaj({
    "sorted(...)[:5]": lambda: sorted(odleglosci)[:5],
    "heapq.nsmallest(5, ...)": lambda: heapq.nsmallest(5, odleglosci),
    "min (gdy k = 1)": lambda: [min(odleglosci)]},
    zgodne=lambda a, b: a[0] == b[0])
wariant                       czas  przyspieszenie
sorted(...)[:5]            8.59 ms            1.0×
heapq.nsmallest(5, ...)     523 µs             16×
min (gdy k = 1)             377 µs             23×

The heap is many times faster than sorting the whole list. When only a single nearest neighbor is needed, a plain min is enough.

Building lists: append or l = l + [x]#

The first version of the function collatz in Altenkirch and Triguero’s book adds successive terms with the statement l = l + [n]. This looks innocent, but l + [n] creates a new list and copies all the existing elements into it. Building a list of length \(n\) therefore costs \(1+2+\dots+n\approx n^2/2\) copy operations. The method append adds the element in place, in constant time on average. A list reserves spare memory and enlarges it from time to time, in proportion to its length. Let us measure the running times for growing \(n\):

def doklejanie(n):
    l = []
    for k in range(n):
        l = l + [k]
    return l


def dopisywanie(n):
    l = []
    for k in range(n):
        l.append(k)
    return l


def skladana(n):
    return [k for k in range(n)]


rozmiary = [2500, 5000, 10000, 20000]
serie = {"l = l + [x]": [zmierz(doklejanie, n) for n in rozmiary],
         "l.append(x)": [zmierz(dopisywanie, n) for n in rozmiary],
         "lista składana": [zmierz(skladana, n) for n in rozmiary]}
assert doklejanie(1000) == dopisywanie(1000) == skladana(1000)
print(f"{'n':15}", "  ".join(f"{n:>8}" for n in rozmiary),
      "  czas(2n)/czas(n)")
for nazwa, t in serie.items():
    print(f"{nazwa:15}", "  ".join(czas(v).rjust(8) for v in t),
          f"  {(t[-1] / t[0]) ** (1 / 3):10.1f}")
wykres_skalowania(rozmiary, serie, "Budowanie listy długości n")
n                   2500      5000     10000     20000   czas(2n)/czas(n)
l = l + [x]      2.90 ms   14.8 ms   73.5 ms    329 ms          4.8
l.append(x)      28.5 µs   55.5 µs    112 µs    222 µs          2.0
lista składana   22.7 µs   46.5 µs   94.0 µs    175 µs          2.0
../_images/e9cbc5d28ef91e64f7b5228d41a7a59a5ba5eb8f3c8e5cfb276af5fed8cf4ba8.png

When \(n\) doubles, the running time of l = l + [x] roughly quadruples, while that of append doubles. On the log-log plot, this shows up as slopes \(2\) and \(1\). The list comprehension is even faster than append, because it does not call a method at every step. A quadratic cost hidden in innocent-looking code is the most common reason why programs run fine on small data and “hang” on large data.

Strings: join and +=#

For the same reason, textbooks recommend concatenating strings with "".join(...) rather than with += in a loop. Strings in Python are immutable, so s += t ought to create a new string. Let us check how the running time grows when we add to the end, when we add to the beginning, and when we use join:

kawalki = [str(k) for k in range(4 * 10**5)]


def na_koncu(xs):
    s = ""
    for x in xs:
        s += x
    return s


def na_poczatku(xs):
    s = ""
    for x in reversed(xs):
        s = x + s
    return s


czasy_napisy = porownaj({"s += x (na końcu)": na_koncu,
                         "s = x + s (na początku)": na_poczatku,
                         "join": "".join}, kawalki[:20000])
for f in (na_koncu, na_poczatku):
    t1, t4 = zmierz(f, kawalki[:20000]), zmierz(f, kawalki[:80000])
    print(f"{f.__name__}: czterokrotnie dłuższe dane, czas × {t4 / t1:.1f}")
wariant                       czas  przyspieszenie
s += x (na końcu)           480 µs            1.0×
s = x + s (na początku)    18.9 ms           0.03×
join                       59.6 µs            8.0×
na_koncu: czterokrotnie dłuższe dane, czas × 3.9
na_poczatku: czterokrotnie dłuższe dane, czas × 12.7

The result is more interesting than the textbook rule. Adding to the end scales linearly: CPython extends the string in place when nothing else holds a reference to it. This, however, is an implementation detail, not a guarantee of the language. The PEP 8 style guide explicitly advises against relying on it, because Python implementations without reference counting do not have it. Adding to the beginning scales quadratically, because each step copies the whole string. The function join is the fastest in all cases, because it first computes the length of the result and then copies each piece once. The conclusion: join is the safe choice, and measurement shows when the difference really matters.

Combinatorics: itertools and math#

The itertools module provides ready-made combinatorial iterators: product, permutations, combinations. In Lecture 6 (§6.3), this is how product enumerates the exponents of the monomials up to a given degree. Is a ready-made iterator faster than a loop? Let us compare three tasks: listing all the permutations of \(8\) elements (our own recursion in the spirit of the chapter on combinatorics in Altenkirch and Triguero’s book, against itertools.permutations), listing the pairs \(i<j\), and counting the triples \(i<j<k\).

def permutacje(xs):
    if len(xs) <= 1:
        yield tuple(xs)
        return
    for i, x in enumerate(xs):
        for reszta in permutacje(xs[:i] + xs[i + 1:]):
            yield (x,) + reszta


def pary_petle(n):
    return [(i, j) for i in range(n) for j in range(i + 1, n)]


def trojki_petle(n):
    return sum(1 for i in range(n) for j in range(i + 1, n)
               for k in range(j + 1, n))


def trojki_combinations(n):
    return sum(1 for _ in itertools.combinations(range(n), 3))


czasy_perm = porownaj({
    "własna rekurencja": lambda: list(permutacje(list(range(8)))),
    "itertools.permutations": lambda: list(itertools.permutations(range(8)))})
czasy_pary = porownaj({
    "dwie pętle": lambda: pary_petle(1000),
    "itertools.combinations":
        lambda: list(itertools.combinations(range(1000), 2))})
czasy_trojki = porownaj({"trzy pętle": trojki_petle,
                         "combinations": trojki_combinations,
                         "math.comb(100, 3)": lambda n: math.comb(n, 3)}, 100)
wariant                      czas  przyspieszenie
własna rekurencja         17.8 ms            1.0×
itertools.permutations    1.05 ms             17×
wariant                      czas  przyspieszenie
dwie pętle                15.6 ms            1.0×
itertools.combinations    11.3 ms            1.4×
wariant                 czas  przyspieszenie
trzy pętle           2.20 ms            1.0×
combinations         3.36 ms           0.66×
math.comb(100, 3)    43.8 ns          50236×

For permutations, the ready-made iterator wins many times over, because our own recursion creates a multitude of intermediate lists and tuples. For pairs, the difference is small, and for counting triples the iterator does not win clearly, because combinations creates a tuple for each triple, which we do not use anyway. The gain from itertools is above all readability and laziness. Speed comes only when the iterator replaces a lot of work done in Python. Orders of magnitude come only from mathematics: the number of triples is given by the formula \(\binom{100}{3}\).

math and pow: exact functions on integers#

The math module has functions that compute exactly with integers of any size: isqrt, gcd, lcm, comb, perm, factorial, prod. Replacing them with computations on float numbers can be not only slower but also wrong. The integer part of a square root computed via float is wrong when the number has more than \(15\)–\(16\) digits:

n = 10**16 - 1
print("int(math.sqrt(n)) =", int(math.sqrt(n)),
      "  math.isqrt(n) =", math.isqrt(n))
print("sprawdzenie isqrt:", math.isqrt(n)**2 <= n < (math.isqrt(n) + 1)**2)
int(math.sqrt(n)) = 100000000   math.isqrt(n) = 99999999
sprawdzenie isqrt: True

The number \(10^{16}-1\) is not a machine number, so float(n) rounds it to \(10^{16}\), whose square root is exactly \(10^8\). Yet \((10^8)^2>n\), so the correct answer is \(10^8-1\).

With a third argument, the built-in function pow computes a power modulo \(m\) by fast exponentiation. It performs about \(\log_2 b\) multiplications of numbers smaller than \(m\). The expression a**b % m first computes the whole power, which for \(b=10^6\) has hundreds of thousands of digits, and only then divides:

m = 1_000_003
print("3**(10**6) ma", math.floor(10**6 * math.log10(3)) + 1, "cyfr")
czasy_pow = porownaj({"3**(10**6) % m": lambda: 3**(10**6) % m,
                      "pow(3, 10**6, m)": lambda: pow(3, 10**6, m)})
print("odwrotność 3 modulo m: pow(3, -1, m) =", pow(3, -1, m),
      "  sprawdzenie:", 3 * pow(3, -1, m) % m)
3**(10**6) ma 477122 cyfr
wariant                czas  przyspieszenie
3**(10**6) % m      43.7 ms            1.0×
pow(3, 10**6, m)     447 ns          97716×
odwrotność 3 modulo m: pow(3, -1, m) = 666669   sprawdzenie: 1

The three-argument pow is more than ten thousand times faster. The Fermat primality test and RSA cryptography rest on it. Since Python 3.8, pow(a, -1, m) also computes the inverse modulo \(m\).

We computed the number of digits of the power with the formula \(\lfloor b\log_{10}3\rfloor+1\), not with len(str(...)). Since version 3.11, Python refuses to convert an integer with more than \(4300\) digits to a string and raises ValueError. This protects servers against attacks in which someone submits a gigantic number for conversion. Python stores integers in binary, and the conversion to decimal notation and back cannot be done in linear time, so for very long numbers it takes a long time. The limit can be changed with the function sys.set_int_max_str_digits.

Summary#

  • Before you write a loop, check the built-in functions and the standard library: sum, math.fsum, Counter, heapq, bisect, itertools, math, pow. They are usually faster, and often more accurate, too (fsum, isqrt).

  • The data structure determines the complexity: in on a list is \(O(n)\), on a set or in a dictionary \(O(1)\) on average, and in a sorted list with bisect \(O(\log n)\).

  • Watch out for a quadratic cost hidden in innocent-looking code: l = l + [x] in a loop, adding to the beginning of a string. Use append, list comprehensions, and join.

  • Popular rules are worth checking by measurement: += at the end of a string is not quadratic in CPython, and itertools is not always faster than a loop.

Exercises#

  1. ★ Write a function that computes the \(\gcd\) of many numbers in a loop, calling math.gcd with two arguments, and compare it with math.gcd(*liczby) for \(10^5\) random numbers.

  2. ★ Count the pairs of last digits of consecutive primes below \(10^7\). Does the unevenness grow or shrink?

  3. ★★ Implement the Fermat primality test: \(n\) is “probably prime” if \(a^{n-1}\equiv1\pmod n\) for several random \(a\). Compare the running times of pow(a, n - 1, n) and a**(n - 1) % n for \(n\) with \(50\) digits. Find the smallest Carmichael number that fools this test.

  4. ★★ For a list of length \(n\), compare x in lista with x in set(lista), including the construction of the set every time. After how many queries does building the set pay off?