|
| 1 | +# https://en.wikipedia.org/wiki/Run-length_encoding |
| 2 | + |
| 3 | + |
| 4 | +def run_length_encode(text: str) -> list: |
| 5 | + """ |
| 6 | + Performs Run Length Encoding |
| 7 | + >>> run_length_encode("AAAABBBCCDAA") |
| 8 | + [('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)] |
| 9 | + >>> run_length_encode("A") |
| 10 | + [('A', 1)] |
| 11 | + >>> run_length_encode("AA") |
| 12 | + [('A', 2)] |
| 13 | + >>> run_length_encode("AAADDDDDDFFFCCCAAVVVV") |
| 14 | + [('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)] |
| 15 | + """ |
| 16 | + encoded = [] |
| 17 | + count = 1 |
| 18 | + |
| 19 | + for i in range(len(text)): |
| 20 | + if i + 1 < len(text) and text[i] == text[i + 1]: |
| 21 | + count += 1 |
| 22 | + else: |
| 23 | + encoded.append((text[i], count)) |
| 24 | + count = 1 |
| 25 | + |
| 26 | + return encoded |
| 27 | + |
| 28 | + |
| 29 | +def run_length_decode(encoded: list) -> str: |
| 30 | + """ |
| 31 | + Performs Run Length Decoding |
| 32 | + >>> run_length_decode([('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)]) |
| 33 | + 'AAAABBBCCDAA' |
| 34 | + >>> run_length_decode([('A', 1)]) |
| 35 | + 'A' |
| 36 | + >>> run_length_decode([('A', 2)]) |
| 37 | + 'AA' |
| 38 | + >>> run_length_decode([('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)]) |
| 39 | + 'AAADDDDDDFFFCCCAAVVVV' |
| 40 | + """ |
| 41 | + return "".join(char * length for char, length in encoded) |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + from doctest import testmod |
| 46 | + |
| 47 | + testmod(name="run_length_encode", verbose=True) |
| 48 | + testmod(name="run_length_decode", verbose=True) |
0 commit comments