MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / run_length_encode

Function run_length_encode

data_compression/run_length_encoding.py:4–26  ·  view source on GitHub ↗

Performs Run Length Encoding >>> run_length_encode("AAAABBBCCDAA") [('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)] >>> run_length_encode("A") [('A', 1)] >>> run_length_encode("AA") [('A', 2)] >>> run_length_encode("AAADDDDDDFFFCCCAAVVVV") [('A', 3), ('D', 6),

(text: str)

Source from the content-addressed store, hash-verified

2
3
4def 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
29def run_length_decode(encoded: list) -> str:

Callers

nothing calls this directly

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected