Search code examples
pythonpython-3.xrun-length-encoding

Encoding and Decoding using RLE and Python 3.7


I have been given a task in my Computer Science lesson to encode and decode ASCII art using RLE. It must output it like "07A05B08C11D" for AAAAAABBBBBCCCCCCCCDDDDDDDDDDD". It must show 0 before numbers/amounts under 10 but I cannot find a tutorial/explanation on how to do this - they do not explain the 0's. Additionally it must take the ASCII art from a text file not input in IDLE. It must also reverse this process with an input using 0's.

Any help with this would be great. Thanks in advance.


Solution

  • You could use itertools.groupby for the run-length encoding and an f-string for formatting single digit numbers:

    from itertools import  groupby
    
    s = "AAAAAABBBBBCCCCCCCCDDDDDDDDDDD"
    
    result = ''.join(f'{sum(1 for _ in group):02}{k}' for k, group in groupby(s))
    
    print(result)
    

    Output

    06A05B08C11D
    

    This statement sum(1 for _ in group) is for counting the numbers of element in each group.