Run Length Encoding - Fix it

Project #1

There is a bug in the code below. Fix it.

Are there any limitations to the encode code function?

Project #2

Fill in the decode function.

Are there any limitations to the decode function?

Code

#!/usr/bin/python3 # ============================================================== # data compression demo (run-length encoding) # -------------------------------------------------------------- # Note: Using the itertools would make this code more efficient, # but efficiency it is not the purpose of this problem. # (docs.python.org/3/library/itertools.html) # ============================================================== import user_interface as ui # -------------------------------------------------------------- # ---- run-length encode a string # ---- 1. traverse the input data # ---- 2. count the number of consecutive repeating characters # ---- (run length) # ---- 3. store the character and its run length # -------------------------------------------------------------- def rle_encode(sring:str) -> str: slen = len(string) if slen == 0: return '' # ---- create encoded pairs encoded = [] char = string[0] count = 0 for i in range(len(sring)-1): if string[i] == char: count += 1 else: encoded.append(str(count)) encoded.append(char) char = string[i] count = 1 # ---- add one last encoded pair? if count > 0: encoded.append(str(count)) encoded.append(char) return ''.join(encoded) # return an encoded string # -------------------------------------------------------------- # ---- decode a run-length encoded string # ---- 1. traverse the encoded data # ---- 2. for each count-character pair, repeat the character # ---- count times # ---- 3. append these characters to the result string # -------------------------------------------------------------- def rle_decode(encoded:str) -> str: # code here return '??????????????' # -------------------------------------------------------------- # ---- test # -------------------------------------------------------------- def test(): line = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWW' +\ 'WWWWWWWWWWWWWWWWWWBBWWWWWWWWWWWWWW' encoded_str = rle_encode(line) print(encoded_str) ##decoded_str = rle_decode(encoded_str) ##print(decoded_str) # -------------------------------------------------------------- # ---- main # -------------------------------------------------------------- if __name__ == '__main__': ##test() while True: s = ui.get_user_input('Enter string: ') if not s: break encoded_str = rle_encode(s) print(encoded_str) ##decoded_str = rle_decode(encoded_str) ##print(decoded_str)

links

Run-length encoding (Wikipedia)