Run-length encoding in Python
Run-length encoding: the simplest compression scheme there is.
def encode(text):
if not text:
return []
runs = [[text[0], 1]]
for ch in text[1:]:
if ch == runs[-1][0]:
runs[-1][1] += 1
else:
runs.append([ch, 1])
return [(ch, count) for ch, count in runs]
How it works
- Starts a run with the first character.
- Repeats extend the current run; a new character starts a new run.
- Returns the runs as
(character, count)pairs.
Keywords and builtins used here
defelseencodeforifreturn
The run, in numbers
- Lines
- 10
- Characters to type
- 191
- Tokens
- 83
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 50 seconds.
Step 4 of 5 in Algorithms, step 54 of 72 in Language basics.