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.

Run-length encoding — the forgotten last run execution-derived · CPython
8    else:
variables
state after line 1 runs
variablevalue
pixels["W","W","W","B","B","W"]
step 1 / 24

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.

Every state you see came from running the program under CPython's tracer at build time — see how GlassBox stays honest.