Fix the Run-Length Encoder
Intermediate · Fix the bug · from Data Compression: Lossless vs Lossy, with Run-Length Encoding
From the lesson: How does run-length encoding work?
The pixel row compresses well because it is full of redundancy: parts of the data repeat or are easy to predict. Ten W's in a row carry little more information than "ten W's". Run-length encoding (RLE) uses exactly that kind of redundancy. A run is a stretch of the same symbol repeated.
Read this part of the lessonThis rle_encode(text) should return the run-length code of text as a string: the count followed by the symbol, for every run. For 'AAAABBC' it should return '4A2B1C', but it returns '4A2B'. Find the bug and fix it.
The text never contains digits.
def rle_encode(text):
if text == "":
return ""
result = ""
current = text[0]
count = 0
for symbol in text:
if symbol == current:
count += 1
else:
result += f"{count}{current}"
current = symbol
count = 1
return result
What Check runs
Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| print(rle_encode("AAAABBC")) | 4A2B1C |
| print(rle_encode("ZZZZ")) | 4Z |
| print(rle_encode("WWWWWWWWWWWWB")) | 12W1B |
More Data Compression exercises
- Measure the SavingBeginner
- Decode Run-Length TextIntermediate