Run-length encoding
Run-length encoding is the bridge between the two halves of this course: it is lossless compression and a traceable program in one artifact. Walk a row of pixels, count each run of one colour, and store it as a (length, colour) pair. Watch out fill up — and watch the most common bug quietly drop the last run.
Compress a row of pixels by replacing each run of the same colour with a (length, colour) pair.
8 else:| variable | value |
|---|---|
pixels | ["W","W","W","B","B","W"] |
Click a line, drag the slider, or use the ← → keys.
What you are looking at
Six pixels — W W W B B W — should compress to three pairs:[3, W] [2, B] [1, W]. The encoder only saves a run when the colour changes, so the very last run needs one extra save after the loop.
- Buggy — saves a run only on a colour change, and the loop ends on a colour that never changes again. The final
[1, W]is never saved;outends with two pairs instead of three. Decode it and the image comes back wrong. - Procedural — the same loop plus one
out.appendafter it, to flush the last run. Nowoutholds all three pairs and round-trips back to the original row.
Every state you see came from running the program under CPython's tracer at build time — see how GlassBox stays honest.