Today's Freebie. It's marked as easy.

This problem was asked by Amazon.

Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".

Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.

Follow

Another Python Using Generators 

"""Example using generators for run length encode/decode."""

def rleunits(str1):
"""Generate run length encoded units."""
current = None
count = 0

for letter in str1:
if letter == current:
count += 1
else:
if current:
yield str(count)+current
count = 1
current = letter

def rldunits(str1):
"""Generate run length decoded units."""
count = None

for c in str1:
if c.isdigit():
if not count:
count = c
else:
count += c
else:
yield(c * int(count))
count = None

def main():
"""Drive the example."""
str1 = "AAAABBBBCDDEEFFFFFFFFFFF"

encoded = ''.join(rleunits(str1))
print(encoded)

unencoded = ''.join(rldunits(encoded))
print(unencoded)

main()

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.