Skip to content

Run length encoding #6492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 2, 2022
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions compression/run_length_encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# https://en.wikipedia.org/wiki/Run-length_encoding


def run_length_encode(input: str) -> list:
"""
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), ('F', 3), ('C', 3), ('A', 2), ('V', 4)]
"""
encoded = []
count = 1

for i in range(len(input)):
if i + 1 < len(input) and input[i] == input[i + 1]:
count += 1
else:
encoded.append((input[i], count))
count = 1

return encoded


def run_length_decode(input: list) -> str:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://docs.python.org/3/library/functions.html#input is a builtin function in Python so please pick a different variable name.

"""
Performs Run Length Decoding
>>> run_length_decode([('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)])
'AAAABBBCCDAA'
>>> run_length_decode([('A', 1)])
'A'
>>> run_length_decode([('A', 2)])
'AA'
>>> run_length_decode([('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)])
'AAADDDDDDFFFCCCAAVVVV'
"""
decoded = ""

for i in input:
decoded += i[0] * i[1]

return decoded


if __name__ == "__main__":
from doctest import testmod

testmod(name="run_length_encode", verbose=True)
testmod(name="run_length_decode", verbose=True)