# Pythonic laziness: good practice and fast code

> *“Premature optimization is the root of all evil.”* — Donald E. Knuth, 1974

In Python the same result can be computed in many ways, and the running times of different programs
can differ by several orders of magnitude. This chapter shows that the fastest program is usually
the one written “lazily,” in both senses of the word. **Programmer’s laziness** is the principle of
not computing what can be derived and not writing what has already been written. Instead of a loop
we use a formula; instead of our own function, a ready-made one from the standard library, NumPy,
SciPy, or SymPy. **Lazy evaluation** means computing values only when they are needed: generators
and iterators stop working as soon as they know the answer, and they do not keep everything in
memory.

All the examples come from the code of the course’s lectures and labs: Horner’s scheme and
bisection, Newton’s method, interpolation and quadrature from Lecture 5; Gaussian elimination from
Lecture 6; MiniCAS from Lecture 3; the kNN model from Lecture 8; the Game of Life from Lab 8. The
starting point is the instructor’s study of Python performance (a comparison of a loop and a
generator), and some of the examples draw on the book by T. Altenkirch and I. Triguero
*Conceptual Programming with Python* (2020). Every timing in this chapter is **measured when the
page is built**, and a hidden code cell checks the sentences about timings at every build.

* {doc}`p1_pomiar` — how to measure time honestly: the contract, `%timeit`, the median of many
  measurements, a loop in a cell vs. in a function, measurement pitfalls, the profiler.
* {doc}`p2_algorytm` — mathematics and the algorithm first: a formula instead of a loop, a cache
  for recursion (`@cache`), parametrization instead of search, the search order in sudoku.
* {doc}`p3_leniwosc` — generators and iterators: short-circuiting `any`/`all`, memory, infinite
  sequences, the lazy sieve of Eratosthenes and its limits.
* {doc}`p4_biblioteka` — the standard library: `sum` and `math.fsum`, a set instead of a list,
  `Counter`, `heapq`, `itertools`, `math.isqrt`, `pow` with a modulus, building lists and strings.
* {doc}`p5_numpy` — NumPy: the loop moved to C, vectorization over independent tasks, pitfalls
  (`np.vectorize`, integer overflow, memory in broadcasting).
* {doc}`p6_scipy` — ready-made algorithms: LAPACK and BLAS, `brentq`, barycentric interpolation,
  `quad`, exact computation and verification, which is cheaper.
* {doc}`p7_sympy` — SymPy: symbolic computation done once, `lambdify`, `Poly`, a specific
  operation instead of `simplify`, rational numbers and binary splitting.
* {doc}`p8_sciaga` — a cheat sheet: the ladder of laziness (the order of decisions), correctness
  pitfalls in mathematical code, readable code, a summary of part 9, references.
* {doc}`p9_kompilacja` — compilation and parallel computing: Numba, a compiler that finds the
  formula by itself, loops that cannot be vectorized, threads, processes, and `prange`, Amdahl’s
  law.

## Map of examples

| Example | What it shows | Where | Connection to the course |
|---|---|---|---|
| two programs summing $i+j$ | the same loop runs faster in a function than in a notebook cell | {doc}`part 1 <p1_pomiar>` | the instructor’s study |
| $S(n)=n^2(n-1)$ | the formula is orders of magnitude faster than any loop | part 1 | Lecture 1, §1.2 |
| profile of the trapezoidal rule | the time goes into the `subs` substitutions | parts 1 and 7 | Lecture 5, §5.4 |
| power sums $1^p+\dots+n^p$ | a formula instead of a loop | {doc}`part 2 <p2_algorytm>` | Lecture 5, §5.3 |
| $\binom{49}{6}$ recursively | tens of millions of calls; `@cache` | part 2 | Altenkirch, Triguero; Lecture 1 |
| Collatz steps for $n\le10^5$ | memoizing results inside a loop | part 2 | Lecture 1, Lab 8 |
| Pythagorean triples | Euclid’s parametrization instead of three loops | part 2 | Lecture 1, §1.2 |
| sudoku | the search order, a solution checker | part 2 | Altenkirch, Triguero; Lectures 7 and 8 |
| the Collatz sequence with `yield` | a generator stops once it knows the answer | {doc}`part 3 <p3_leniwosc>` | Altenkirch, Triguero |
| $n^2+n+41$ | a counterexample to Euler’s polynomial, found lazily | part 3 | |
| the lazy sieve of Eratosthenes | `RecursionError` and a “sieve” that is not one | part 3 | Altenkirch, Triguero; O'Neill |
| $H_n>10$ | a lazy pipeline of `accumulate` and `next` | part 3 | |
| a million copies of `0.1` | `sum` and `math.fsum`: faster and more accurate | {doc}`part 4 <p4_biblioteka>` | Lecture 1, §1.4; IEEE 754 |
| `in` on a list and on a set | the data structure determines the complexity | part 4 | Lecture 8, §8.3 |
| last digits of consecutive primes | `Counter`; the Lemke Oliver–Soundararajan phenomenon | part 4 | |
| `l = l + [x]` | a hidden quadratic cost | part 4 | Altenkirch, Triguero |
| $10^{16}-1$ | `math.isqrt` computes exactly, `float` does not | part 4 | Lecture 1 |
| `pow(3, 10**6, m)` | modular exponentiation instead of a huge power | part 4 | |
| Horner’s scheme on an array | the same function on an array, the same bits | {doc}`part 5 <p5_numpy>` | Lecture 5, §5.1 |
| Newton basins | vectorization over the starting points | part 5 | Lecture 5, §5.2 |
| the Game of Life | `np.roll` faster than loops and than SciPy’s convolution | part 5 | Lab 8 |
| $25!$ in NumPy | integer overflow without a warning | part 5 | the instructor’s study; Lecture 1 |
| the sum of all pairwise distances | a formula after sorting instead of an $n\times n$ matrix | part 5 | |
| Gaussian elimination | LAPACK; the advantage grows with the size | {doc}`part 6 <p6_scipy>` | Lecture 6, §6.1 |
| checking $Ax=b$ | checking is cheaper than computing | part 6 | Lectures 3, 5, 6 |
| bisection vs. `brentq` | fewer evaluations of an expensive function | part 6 | Lecture 5, §5.1 |
| the barycentric form | $O(n)$ operations per point instead of $O(n^2)$ | part 6 | Lecture 5, §5.3 |
| the trapezoidal rule vs. `quad` | machine precision after a few dozen function values | part 6 | Lecture 5, §5.4; Lab 7 |
| $\sin(x+1)+\cos(x+1)$ at a thousand points | from `subs` to `lambdify`: four orders of magnitude | {doc}`part 7 <p7_sympy>` | Lecture 3, §3.4 |
| `Poly` | polynomials without expression trees | part 7 | Lecture 3, §3.3 |
| `expand(...) == 0` | a decision procedure instead of a heuristic | part 7 | Lecture 5, §5.3; Richardson’s theorem |
| $H_{2000}$ exactly | binary splitting; `sp.harmonic` keeps its own cache | part 7 | |
| `[[0] * n] * n` and others | correctness pitfalls | {doc}`part 8 <p8_sciaga>` | Lecture 6 |
| the double loop from part 1 in Numba | the compiler itself turns the loops into the formula $n^2(n-1)$ | {doc}`part 9 <p9_kompilacja>` | Lecture 1, §1.2 |
| Collatz steps for $n\le10^7$ | a loop that cannot be vectorized; compilation and a table of known results | part 9 | Lecture 1, Lab 8 |
| Gaussian elimination in Numba | compilation does not replace LAPACK | part 9 | Lecture 6, §6.1 |
| $21!$ and a million copies of `0.1` in Numba | 64-bit integers; `fastmath` changes the result | part 9 | Lecture 1; IEEE 754 |
| threads, processes, and `prange` | the global interpreter lock (GIL), the cost of starting processes, performance and efficiency cores | part 9 | the instructor’s study |

## How to read this chapter

* Lecture 1 and basic Python are enough. The parts can be read independently. Part 1 describes the
  measuring tool `porownaj`, which parts 2–7 and 9 use.
* The chapter uses examples from the whole semester, including lectures that are still to come.
  Such an example is worth revisiting after the corresponding lecture.
* The timings come from the computer on which the page was built (the line describing it at the
  beginning of each part), and they change with every build. What matters are the ratios of times
  and how the time grows with the size of the data. Differences of a few percent are noise.
* The notebooks can be downloaded and run on your own computer (the button at the top of the
  page). You need NumPy, SciPy, SymPy, and Matplotlib, and for part 9 also Numba
  (`pip install numba`). One comparison in part 7 also uses the MiniCAS package from Lecture 3.
