Run Length Encoding Round Trip
Encode runs of repeated characters as count-plus-char pairs and expand them back, rejecting a dangling trailing count instead of dropping it.
Code
def encode(text):
"""Collapse each run of repeated characters into count + character."""
runs = []
for char in text:
if runs and runs[-1][1] == char:
runs[-1][0] += 1
else:
runs.append([1, char])
return "".join(f"{count}{char}" for count, char in runs)
def decode(encoded):
"""Expand count + character pairs back into the original text."""
decoded = []
digits = ""
for char in encoded:
if char.isdigit():
digits += char
else:
decoded.append(char * int(digits))
digits = ""
if digits:
raise ValueError(f"dangling count {digits!r} without a character")
return "".join(decoded)
source = "aaabbcdddd"
packed = encode(source)
print("encoded:", packed)
print("decoded:", decode(packed))
print("round trip preserved:", decode(packed) == source)
print("singles stay explicit:", encode("abc"))
try:
decode("3a2")
except ValueError as err:
print("rejected:", err)Output
Captured from a sandboxed run of this snippet in the build pipeline.
encoded: 3a2b1c4d
decoded: aaabbcdddd
round trip preserved: True
singles stay explicit: 1a1b1c
rejected: dangling count '2' without a characterWhat the code does
Run Length Encoding Round Trip is built around the functions encode and decode.
The file repeats itself only inside for char in text. The failure path is explicit — ValueError is raised when the guard condition holds.
What to watch for
- The guard
digitsshort-circuits the flow with an earlyraisewhen its condition holds.
Applying it
The entry-point signature is def encode(text)
Output lines are prefixed (encoded:, decoded:, round trip preserved:), making each step’s effect easy to spot.
encode is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
except ValueError as err:
print("rejected:", err)
def encode(text):
"""Collapse each run of repeated characters into count + character."""
runs = []
for char in text:
if runs and runs[-1][1] == char:
runs[-1][0] += 1
else:
runs.append([1, char])
return "".join(f"{count}{char}" for count, char in runs)
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- How does the snippet fail?
- The code refuses to continue: `ValueError` is thrown while the state is still recoverable.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `encode`, `decode` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.