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:
encode(text)returns the run-length encoded version oftext.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
decodemust 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" * 3is"ababab".- A good test:
decode(encode(text))should always give backtext.