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

SPOILER ONE-LINER SOLUTIONS IN PYTHON 

import re

encooded = "14A3B2C1D2A"
decoded = ""

# first attempt at decoding
list1 = re.findall('\d+\D', encooded)
for l in list1:
count, char = int(l[0:-1]) , l[-1]
decoded += ''.join(count * char)
print(decoded)

# one-liner using regex for decoding!
print(''.join([ int(l[0:-1]) * l[-1] for l in re.findall('\d+\D', encooded) ]))

# one liner using regex for encoding
print( ''.join([ str(len(match[1])+1) + match[0] for match in re.findall(r"(.)(\1*)", decoded)]))

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.