# Python puzzle cookbook

Each recipe runs on synthetic input. Examples use Python 3.11 or later except where marked. Imports from `elf.helpers` are optional.


# Working with puzzle input


## Keep the spaces that describe a map

A space at the left edge can be a real column. Use `splitlines()` to drop line endings while keeping the contents of each row. A blank line can then separate the map from its instructions.

``` python
text = " A.\r\n..B\r\n\r\nwalk  2\r\n"
lines = text.splitlines()
divider = lines.index("")
grid = [list(row) for row in lines[:divider]]
action, count = lines[divider + 1].split()
assert grid[0] == [" ", "A", "."]
assert (action, int(count)) == ("walk", 2)
```

For repeated groups, apply the same split rule at every blank line. This version ignores runs of empty lines and keeps a final group without a trailing separator.

``` python
from itertools import groupby

lines = "red\nblue\n\n\ngreen".splitlines()
groups = [list(group) for has_text, group in groupby(lines, key=bool) if has_text]
assert groups == [["red", "blue"], ["green"]]
```

In an elf daily file, `data` is already the result of `parse_input(text)`, which uses `splitlines()`. For local files, `read_input(Path("input.txt"))` strips whitespace at both ends of the **whole file**. Use `Path("input.txt").read_text(encoding="utf-8")` when that whitespace matters.


## Match the parser to the delimiter

For a known format, unpack the fields. Use a regex when the integers can appear anywhere in a label.

``` python
import re

numbers = list(map(int, " 8   -3  12 ".split()))
name, limits = "gate:3-5".split(":")
low, high = map(int, limits.split("-"))
assert (name, low, high) == ("gate", 3, 5)

coords = [int(s) for s in re.findall(r"[+-]?[0-9]+", "row=-2 col=+5")]
assert coords == [-2, 5]
```

Elf's `ints(text)` uses that regex. It reads embedded digits and attaches the nearest adjacent sign. For example, `ints("v2: 3-5, --7")` gives `[2, 3, -5, -7]`. Split range endpoints explicitly when the hyphen is a separator. [Python regular expressions](https://docs.python.org/3/library/re.html)


# Collections and counting


## Keep order, count visits, or compare routes

A list retains every visit. A tuple works as a dictionary key for a coordinate. A set answers membership questions, and dictionary keys can remove duplicates while preserving the order of first appearance.

``` python
from collections import Counter, defaultdict

route = [(0, 1), (1, 1), (0, 1)]
first_visits = list(dict.fromkeys(route))
assert first_visits == [(0, 1), (1, 1)]
assert Counter(route).most_common(1) == [((0, 1), 2)]

other_route = {(1, 1), (2, 1)}
assert set(route) & other_route == {(1, 1)}  # shared stops
assert set(route) - other_route == {(0, 1)}  # unique to this route

columns_by_row = defaultdict(list)
for row, col in first_visits:
    columns_by_row[row].append(col)
assert columns_by_row[0] == [1]
```

Use a `deque` when you also need to take items off the front efficiently. The breadth-first search below uses one to process cells in arrival order. [Python collections](https://docs.python.org/3/library/collections.html)


# Iteration and combinations


## Compare neighboring readings

`enumerate` gives a position and its value. `pairwise` gives consecutive values. For a fixed window of three, zip the sequence with two shifted slices. Sum a generator expression when you only need the final count.

``` python
from itertools import pairwise

levels = [3, 1, 4, 6]
positions = [i for i, height in enumerate(levels) if height > 3]
assert positions == [2, 3]
assert sum(b > a for a, b in pairwise(levels)) == 2
windows = [a + b + c for a, b, c in zip(levels, levels[1:], levels[2:])]
assert windows == [8, 11]
```

For **non-overlapping** chunks from an iterable, Python **3.12+** provides `itertools.batched`. The final chunk can be shorter.

``` python
from itertools import batched

assert list(batched("ABCDE", 2)) == [("A", "B"), ("C", "D"), ("E",)]
```


## Choose the candidate space

Choose unordered pairs for handshakes, ordered pairs for directed connections, and a Cartesian product when each selection is independent. Each iterator can feed a loop directly.

``` python
from itertools import combinations, permutations, product

assert list(combinations("ABC", 2)) == [("A", "B"), ("A", "C"), ("B", "C")]
assert len(list(permutations("ABC", 2))) == 6  # A to B differs from B to A
assert list(product("AB", [1, 2])) == [("A", 1), ("A", 2), ("B", 1), ("B", 2)]
```

[Python iterator recipes](https://docs.python.org/3/library/itertools.html)


# Grids and coordinates


## Find a marker and take one legal step

Use `(row, column)` so that `grid[row][col]` reads naturally. Row numbers increase downward. Check both lower bounds before indexing because Python accepts negative indices.

``` python
grid = ["S..", ".#.", "..E"]
start = next((r, c) for r, row in enumerate(grid) for c, ch in enumerate(row) if ch == "S")
r, c = start
adjacent = [(r - 1, c), (r, c - 1), (r, c + 1), (r + 1, c)]
moves = [(r, c) for r, c in adjacent
         if 0 <= r < len(grid) and 0 <= c < len(grid[r]) and grid[r][c] != "#"]
assert moves == [(0, 1), (1, 0)]
```

`neighbors4(start)` gives the same candidates as a tuple. `neighbors8(start)` also includes diagonals. Both scan in reading order, skip the center, and leave boundary checks to you. For four-way travel on an open grid, `manhattan(a, b)` counts steps as `abs(a[0] - b[0]) + abs(a[1] - b[1])`. With walls, this is a lower bound.


## Turn the map or store just the occupied cells

Transpose a rectangular map to process columns as rows. Reverse the rows before transposing to rotate it clockwise. For a mostly empty map, a set can record walls and a dictionary can associate labels with positions.

``` python
rows = ["A.#", "..B"]
columns = ["".join(col) for col in zip(*rows, strict=True)]
clockwise = ["".join(col) for col in zip(*reversed(rows), strict=True)]
assert columns == ["A.", "..", "#B"]
assert clockwise == [".A", "..", "B#"]

labels = {(r, c): ch for r, row in enumerate(rows) for c, ch in enumerate(row) if ch != "."}
walls = {pos for pos, ch in labels.items() if ch == "#"}
assert walls == {(0, 2)}
```

If your moves are mostly turns and steps, complex numbers offer a compact alternative. With columns on the real axis and rows on the imaginary axis, `1` moves east, `1j` moves south, and multiplying a direction by `1j` turns right.


# Graphs and search


## Fewest moves with breadth-first search

When every edge costs one move, the first visit gives the shortest distance. Mark a node when you enqueue it so two paths arriving together cannot queue it twice.

``` python
from collections import deque

links = {"A": "BC", "B": "D", "C": "D", "D": ""}
distance = {"A": 0}
queue = deque(["A"])
while queue:
    node = queue.popleft()
    for dest in links[node]:
        if dest not in distance:
            distance[dest] = distance[node] + 1
            queue.append(dest)
assert distance["D"] == 2
```


## Flood fill and count connected components

To measure regions, visit order can be arbitrary. A list used as a stack gives depth-first search. Remove each cell from the unvisited set as you claim it. Each new seed starts one connected component.

``` python
remaining = {(0, 0), (1, 0), (1, 1), (0, 3)}
sizes = []
while remaining:
    stack = [remaining.pop()]
    size = 0
    while stack:
        r, c = stack.pop()
        size += 1
        for pos in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
            if pos in remaining:
                remaining.remove(pos)
                stack.append(pos)
    sizes.append(size)
assert sorted(sizes) == [1, 3]
```


## Cheapest route with Dijkstra's algorithm

With nonnegative edge costs, use a priority queue. A node can be discovered again at a lower cost. Skip an older heap entry when it no longer matches the cheapest known arrival.

``` python
import heapq

edges = {"A": [("B", 7), ("C", 2)], "B": [], "C": [("B", 1)]}
best = {"A": 0}
frontier = [(0, "A")]
while frontier:
    cost, node = heapq.heappop(frontier)
    if cost != best[node]:
        continue
    for dest, weight in edges[node]:
        candidate = cost + weight
        if dest not in best or candidate < best[dest]:
            best[dest] = candidate
            heapq.heappush(frontier, (candidate, dest))
assert best["B"] == 3
```


## Put prerequisites first

Give `TopologicalSorter` a mapping from task to prerequisites. Several orders may be valid, so check the precedence constraints. A cycle raises `CycleError`. [Python graphlib](https://docs.python.org/3/library/graphlib.html)

``` python
from graphlib import TopologicalSorter

needs = {"pack": {"cut", "fold"}, "fold": {"cut"}}
order = tuple(TopologicalSorter(needs).static_order())
assert order == ("cut", "fold", "pack")
```


# Mathematics


## Count exactly and wrap around

Keep counts and indices as integers. Use `divmod` to split a flat index into row and column, `%` to wrap a position, and fractions when division must stay exact.

``` python
from fractions import Fraction
from math import gcd, lcm, prod

widths = [3, 4, 6]
assert (sum(widths), prod(widths), min(widths), max(widths)) == (13, 72, 3, 6)
assert divmod(17, 5) == (3, 2)
assert (1 - 3) % 5 == 3                     # two steps left on a ring
assert gcd(12, 18) == 6                      # largest equal block size
assert lcm(4, 6) == 12                       # cycles starting together realign
assert Fraction(1, 3) * 3 == 1
```


## Track flags and intersect intervals

A bitmask fits several yes/no flags in one integer. Use half-open intervals `[start, stop)` for spans so that subtracting the endpoints gives their length, just like a Python slice.

``` python
flags = int("0101", 2)
assert flags & (1 << 2)                      # bit 2 is set (numbering from 0)
assert (flags | (1 << 1)).bit_count() == 3

a, b = (2, 7), (5, 9)
overlap = max(0, min(a[1], b[1]) - max(a[0], b[0]))
assert overlap == 2                          # positions 5 and 6
```


# Performance and optimization


## Reduce the number of candidates first

A nested loop comparing every pair of 10,000 items can examine nearly 50 million pairs. To find two entries with a given sum, scan once and look up the complement in a set. Checking before insertion ensures the two entries come from different positions.

``` python
seen = set()
target = 10
for value in [3, 2, 8, 5]:
    if target - value in seen:
        pair = (target - value, value)
        break
    seen.add(value)
else:
    pair = None
assert pair == (2, 8)
```


## Reuse a subproblem or skip a repeated cycle

If different choices reach the same state, cache its result. Here the number of ways to cover a length with tiles of size one or two depends only on the remaining length. Include every input that affects the answer in the cache key.

``` python
from functools import cache

@cache
def ways(left):
    if left <= 1:
        return 1
    return ways(left - 1) + ways(left - 2)

assert ways(5) == 8
```

For a long deterministic simulation, save the **full state** and the step when you first saw it. On a repeat, the distance between the two visits is the period. This skips whole laps even when the starting state is outside the cycle.

``` python
jump = {"A": "B", "B": "C", "C": "D", "D": "B"}
state, step, goal = "A", 0, 1_000_000
first_seen = {}
while step < goal and state not in first_seen:
    first_seen[state] = step
    state = jump[state]
    step += 1
if step < goal:
    period = step - first_seen[state]
    for _ in range((goal - step) % period):
        state = jump[state]
assert state == "B"
```


## Time a cell and profile a whole run

Wrap the expression you are investigating with `perf_counter()`. Keep input loading outside the measured block when comparing algorithms.

``` python
from time import perf_counter

start = perf_counter()
total = sum(i * i for i in range(10_000))
elapsed = perf_counter() - start
print(f"{total=} in {elapsed:.6f}s")
```

If the work already lives in a function, [elf.helpers.timer](../reference/helpers.timer.md#elf.helpers.timer) can report each call.

``` python
from elf.helpers import timer

@timer()
def score(values):
    return sum(v * v for v in values)

assert score([2, 3]) == 13
```

For a surprising slowdown, run the file in sample mode with `python -m cProfile -s cumulative 2026/day02.py`. Look at the functions with high cumulative time **and** their call counts. A search exploring the same state thousands of times often gains more from recording visited states than from speeding up a single iteration.


# Hashing and string manipulation


## Hash exactly the text the puzzle specifies

Encode text before hashing it. A trailing newline changes the digest. For historical puzzles that request MD5, `elf.helpers.md5("abc")` is the shortcut for the following expression. MD5 is unsuitable for cryptographic security.

``` python
from hashlib import md5

digest = md5("abc".encode("utf-8"), usedforsecurity=False).hexdigest()
assert digest[:6] == "900150"
```


## Transform a string in one pass

Use slices to take a prefix or reverse a sequence. Use a translation table for repeated character substitutions, then join pieces to construct the output.

``` python
route = "N E S".split()
opposite = str.maketrans("NESW", "SWNE")
return_route = "".join(route[::-1]).translate(opposite)
assert return_route == "NWS"
```


# Testing and debugging


## Start with a case you can check by hand

Put an intermediate result at module level so Positron's Variables pane or the VS Code debugger can show it. Here you can inspect `rises` when the answer differs from the expected count. An empty input and a one-value input both have zero adjacent pairs.

``` python
# %% Setup
from itertools import pairwise

sample = "3\n1\n4\n"
levels = list(map(int, sample.splitlines()))

# %% Part 1
rises = [(a, b) for a, b in pairwise(levels) if b > a]
assert rises == [(1, 4)]
assert len(rises) == 1
assert list(pairwise([])) == list(pairwise([7])) == []
```

In a generated elf file, enter the sample answers in `SAMPLE_ANSWERS`, run **Setup**, then run the cell selected by `PART`. When switching parts, rerun Setup so the expected answer matches the part. If Part 2 has a different example, replace the inline sample too. Ordinary Python runs these assertions. The `-O` flag disables them.

Once the sample passes, set `USE_SAMPLE = False` and rerun Setup and the selected part with the same parser. Compare the row count, row widths, and first parsed record if the real input behaves differently. These checks often reveal a blank separator or a sign that the small example never exercised.
