Edexcel International Advanced Level Computer Science, point 21.2.2
Run-length encoding (RLE) is a simple, lossless compression method that replaces each run of identical consecutive items with a count and the item. In Unit 4 you must implement and use it in Python.
The idea
AAAABBBCCD is stored as 4A3B2C1D
(10 characters) (8 characters)
- A run is a sequence of the same item.
- Lossless: the original can be rebuilt exactly.
- It works well on data with long runs (simple images, fax pages, icons, repeated text) and badly on data with few repeats.
Encoding
Go through the data, counting each run:
- Start with the first item and a count of 1.
- For each next item: if it matches the current one, add 1 to the count; otherwise, output the count and the item and start a new run.
- After the last item, output the final run.
def rle_encode(text):
if not text:
return ""
result = []
current = text[0]
count = 1
for ch in text[1:]:
if ch == current:
count += 1
else:
result.append(f"{count}{current}")
current = ch
count = 1
result.append(f"{count}{current}") # the final run
return "".join(result)
print(rle_encode("AAAABBBCCD")) # 4A3B2C1D
print(rle_encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBB")) # 12W1B12W3B
print(rle_encode("")) # (empty)
Trace of AAAABBBCCD:
| Character | Current run | Count | Output so far |
|---|---|---|---|
| A | A | 1 | |
| A, A, A | A | 4 | |
| B | new run: output 4A |
1 | 4A |
| B, B | B | 3 | 4A |
| C | output 3B |
1 | 4A3B |
| C | C | 2 | 4A3B |
| D | output 2C |
1 | 4A3B2C |
| (end) | output the final run 1D |
4A3B2C1D |
A common mistake is to forget the final run.
Decoding
Read each count, then repeat the item that many times.
def rle_decode(encoded):
result = []
count = ""
for ch in encoded:
if ch.isdigit():
# build up multi-digit counts
count += ch
else:
result.append(ch * int(count))
count = ""
return "".join(result)
print(rle_decode("4A3B2C1D")) # AAAABBBCCD
# WWWWWWWWWWWWBWWWWWWWWWWWWBBB
print(rle_decode("12W1B12W3B"))
Round-trip check: rle_decode(rle_encode(x)) == x should always be true.
How much space does it save?
Compression ratio .
| Data | Original | Encoded | Result |
|---|---|---|---|
AAAABBBCCD |
10 | 8 | Smaller (ratio 1.25) |
WWWWWWWWWWWWBWWWWWWWWWWWWBBB |
28 | 10 | Much smaller (ratio 2.8) |
ABCD |
4 | 8 (1A1B1C1D) |
Larger! |
AABBCC |
6 | 6 (2A2B2C) |
No saving |
RLE helps only if runs are long (at least 3 or 4 repeats on average). With no repeated neighbours, it doubles the size.
for sample in ["AAAABBBCCD", "ABCD"]:
enc = rle_encode(sample)
print(sample, enc, len(sample), len(enc))
Handling digits in the data
If the original text contains digits, the count-then-character format is ambiguous: rle_decode("11A") could mean eleven A's, or "1" then "1A". Solutions:
- Use a separator:
4,A;3,B(bigger). - Store counts as a fixed-width number (for example 1 byte, 0 to 255).
- Use an escape or marker for literal digits.
- Only use RLE on data without digits (like the examples here).
Binary or byte data: store each run as a pair of bytes: (count, value), with the count limited to 255 per pair, splitting longer runs. For a black-and-white image, use alternating counts: 12 1 12 3 for 12 white, 1 black, 12 white, 3 black.
def rle_encode_pairs(items):
"""Return (count, item) pairs; works for any items."""
pairs = []
for item in items:
if pairs and pairs[-1][1] == item:
pairs[-1][0] += 1
else:
pairs.append([1, item])
return [(c, i) for c, i in pairs]
print(rle_encode_pairs("AAB11")) # [(2, 'A'), (1, 'B'), (2, '1')]
print(rle_encode_pairs([0, 0, 0, 1, 1]))# [(3, 0), (2, 1)]
Pairs have no ambiguity.
Benefits and drawbacks
- Benefits: very simple and fast, lossless, little memory, excellent for data with long runs, and easy to decode.
- Drawbacks: can make data larger (no runs), poor for photos, text and sound, and digits in the data need care.
- Lossless against lossy: RLE loses nothing (like ZIP and PNG), unlike JPEG or MP3.
Test plan
| Test | Data | Expected |
|---|---|---|
| Empty | "" |
"" |
| One character | "A" |
"1A" |
| One long run | "AAAAAAAAAAAA" (12) |
"12A" |
| No repeats | "ABC" |
"1A1B1C" |
| Mixed runs | "AAABCC" |
"3A1B2C" |
| Run at the end | "ABBB" |
"1A3B" |
| A count over 9 | 12 repeats | Multi-digit count read correctly |
| Round trip | Decode the encoding | The original |
tests = ["", "A", "AAAAAAAAAAAA", "ABC", "AAABCC", "ABBB",
"AABBBBBBBBBBBB"]
for t in tests:
assert rle_decode(rle_encode(t)) == t
assert rle_encode("A") == "1A"
assert rle_encode("ABBB") == "1A3B"
print("All RLE tests passed")
Worked example
Task: a 16 × 1 strip of a black-and-white image is WWWWBBWWWWWWWWBB (W = white, B = black). Encode it, work out the compression, and decode it.
strip = "WWWWBBWWWWWWWWBB"
encoded = rle_encode(strip)
print(encoded) # 4W2B8W2B
print(len(strip), len(encoded)) # 16 8
print(rle_decode(encoded) == strip) # True
Runs: 4 W, 2 B, 8 W, 2 B. Encoded: 4W2B8W2B (8 characters), half the original 16: a compression ratio of 2. Decoding gives the same strip back, so it is lossless.
Exam tip: write the encoder with the three steps (start, extend or end the run, output the final run), and don't forget the last run. Show that decoding reverses it. Know when RLE helps and when it makes data bigger. Give the compression ratio.
Check yourself
What is the run-length encoding of WWWBBW?
3W2B1W.
Why is RLE called lossless?
The original data can be rebuilt exactly from the compressed form, so nothing is lost.
When does RLE make data larger?
When there are few or no repeated neighbouring items, because every single item gets a count in front of it.
What is a common mistake when writing an RLE encoder?
Forgetting to output the final run after the loop ends.
Why is RLE not suited to photographs?
Photos have little exact repetition between neighbouring pixels, so there are few long runs to compress.