Run-Length Encoding
Medium · 50 XPCompress a string so aaabccddd becomes a3b1c2d3, then write the decoder and prove it round-trips.
Target output
a3b1c2d3 aaabccddd True
Blank · autosaved
PYrun-length.py
Walk the string tracking the current character and a count; flush when it changes. For decode, pair each letter with the digits that follow it.
def encode(s):
out = ""
count = 1
for i in range(1, len(s) + 1):
if i < len(s) and s[i] == s[i - 1]:
count += 1
else:
out += s[i - 1] + str(count)
count = 1
return out
def decode(s):
out = ""
i = 0
while i < len(s):
ch = s[i]
j = i + 1
while j < len(s) and s[j].isdigit():
j += 1
out += ch * int(s[i + 1:j])
i = j
return out
text = "aaabccddd"
print(encode(text))
print(decode(encode(text)))
print(decode(encode(text)) == text)
Run your code to check it…