Run length encoding and dictionary coding for lossless compression.
1.3.1 Compression, Encryption and Hashing
Compression, Encryption and Hashing — Note 2 of 4
Candidates need to understand how run-length encoding can reduce the size of a file for example with a text file or image. Candidates should understand how dictionary coding works by substituting entries with a unique code. Candidates should have practical experience of using these algorithms with small example files.
Run length encoding and dictionary coding are two lossless compression methods. Both work by finding repetition in the data and storing it more efficiently, so the original can be rebuilt exactly.
Replaces a run of repeated values with a single copy of the value and a count of how many times it repeats.
Frequently occurring words or patterns are replaced by shorter codes, and a dictionary that maps codes to the original patterns is stored with the file.
WWWWWBBBWW gives 5W 3B 2W (or W5B3W2), reducing 10 values to 3 value-count pairs.def rle(data):
result = []
count = 1
for i in range(1, len(data) + 1):
if i < len(data) and data[i] == data[i - 1]:
count = count + 1
else:
result.append(str(count) + data[i - 1])
count = 1
return " ".join(result)
print(rle("WWWWWBBBWW")) # 5W 3B 2WText: the cat sat on the mat the end
Dictionary: 1 = the 2 = cat 3 = sat 4 = on 5 = mat 6 = end
Encoded: 1 2 3 4 1 5 1 6