Data representation · GCSE · OCR J277 1.2.5, AQA 8525 3.3.8, Edexcel 1CP2 2.3.2 · about 20 min
Lossy and lossless; run length encoding and Huffman coding.
[1 mark]Which kind of compression must be used for a program file?
[1 mark]What does lossy compression do?
[1 mark]Run length encode WWWWBBW in the form count then character.
[1 mark]On which data does RLE work worst?
[1 mark]In Huffman coding, which characters get the shortest codes?
Write rle_encode(text) and rle_decode(code) yourself. Encode the row ........######....######........ and print it as encoded: <code>, then print original: <n> characters, encoded: <m> characters, and finally decoded matches: True, using your decode function.
# the two lines every program starts with: the commands, then the robot from bugbot import * connect() row = "........######....######........"
The hint students can ask for: Walk the row counting how long the current run is. When the character changes, write the count and that character, then start counting again. To decode, gather the digits into a number, then repeat the character that follows it.
from bugbot import *
connect()
def rle_encode(text):
out = ""
count = 1
for i in range(1, len(text)):
if text[i] == text[i - 1]:
count = count + 1
else:
out = out + str(count) + text[i - 1]
count = 1
return out + str(count) + text[-1]
def rle_decode(code):
out = ""
number = ""
for ch in code:
if ch.isdigit():
number = number + ch
else:
out = out + ch * int(number)
number = ""
return out
row = "........######....######........"
code = rle_encode(row)
print("encoded:", code)
print("original:", len(row), "characters, encoded:", len(code), "characters")
print("decoded matches:", rle_decode(code) == row)
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.