compress.py
"""
Perform Run Length Encoding compression on a string.
"""
def compress(raw: str) -> bytes:
"""
Compress the raw string to bytes using RLE.
"""
out: list[int] = []
for b in raw.encode('utf-8'):
if out:
byte = out.pop()
if b == byte:
count = out.pop()
out.append(count + 1)
out.append(byte)
else:
out.append(byte)
out.append(1)
out.append(b)
else:
out.append(1)
out.append(b)
return bytes(out)