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.

PythonData Integrity

Code

pythonsnippet
34 lines
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 character

What 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 digits short-circuits the flow with an early raise when 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

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.