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.

Basic non regex solution 

@Absinthe@qoto.org
def encode(input):
out = ""

let = input[0]
num = 1

for i in range(1, len(input)):
if input[i] == input[i-1]:
num = num + 1
else:
out = out + str(num) + input[i-1]
let = input[i]
num = 1

out = out + str(num) + input[len(input)-1]

return out

def decode(input):
out = ""

i = 0

while i != (len(input)):
for p in range(0, int(input[i])):
out = out + input[i+1]
i = i + 2

return out

Follow

Basic non regex solution 

@matrix07012 not sure how you feel about criticism, so I will hold back too much opinion. However, line 4 and 12 are unused.

Basic non regex solution 

@Absinthe@qoto.org No problem, I looked up the proper solution now and mine is clumsier than I thought.

Basic non regex solution 

@matrix07012 I just watched a great video on looping and iterators and perhaps I am a bit more critical of things:

youtube.com/watch?v=EnSu9hHGq5

It might change your life, it will change your code!

BTW, did you check out my generator version?

Basic non regex solution 

@Absinthe@qoto.org I just did, pretty interesting.

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.