Lesson 2 of 8 · 15 min

Challenge: Squash it with run-length encoding

Nisha in Port Louis makes pixel art on her phone and sends it to friends over a slow connection. A row of her picture looks like this, with W for a white pixel and B for a black one:

WWWWWWWWWWWWBWWWWWWWWWWWWBBB

That is a lot of letters to send. Run-length encoding (RLE) squashes each run of the same character into a count and the character:

12W1B12W3B

28 characters became 10. Image formats and fax machines have used this trick for decades.

Your task

Write two functions:

  1. encode(text) returns the run-length encoded version of text.
  2. decode(code) turns an encoded string back into the original text.
encode("WWWWBBBW")   # "4W3B1W"
encode("aab")        # "2a1b"
decode("4W3B1W")     # "WWWWBBBW"
decode("12W1B")      # "WWWWWWWWWWWWB"

Rules

  • Always write the count, even when it is 1: "x" becomes "1x".
  • Counts can be bigger than 9, so decode must read every digit of "12W".
  • Capitals and lowercase letters are different characters: "aAa" is "1a1A1a".
  • Spaces and punctuation are characters too: " !!" is "2 2!".
  • The original text never contains digits. Empty text encodes to "" and decodes to "".

Tips

  • For encode, keep two variables: the character you are counting and the count so far. When the next character is different, write out the run and start a new one. Do not forget the last run after the loop.
  • For decode, keep a string of digits seen so far. ch.isdigit() tells you whether a character is a digit. When you meet a non-digit, int(digits) gives the count.
  • "ab" * 3 is "ababab".
  • A good test: decode(encode(text)) should always give back text.
main.py
def encode(text):
    # TODO: turn runs like "WWWW" into "4W"
    return ""


def decode(code):
    # TODO: turn "4W" back into "WWWW"
    return ""


print(encode("WWWWBBBW"))  # should print 4W3B1W
print(decode("12W1B"))     # should print WWWWWWWWWWWWB

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…