For a school assignment I have to write an encoder and decoder in Python, which takes a string of encoded characters as so : "2k3b" and decodes them into "kkbbb". I have already written the encoder and tested it with pytest, but I can't seem to wrap my head around writing the decoder. The code for the encoder and decoder respectively is posted below.
def encode(mess):
""" Run length encoding - convert string from 'wwwwwwbbbb' til '6w4b'"""
res = []
old_val = mess[0]
count = 0
for char in mess:
if char == old_val:
count += 1
else:
res.append('%d%c' % (count, old_val))
old_val = char
count = 1
res.append('%d%c' % (count, char))
return ''.join(res)
I know that last res.append('%d%c' % (count, char))
is bad coding, but I just had to make it work and i'm not experienced enough in Python.
def decode(mess):
"""Run length decoding - convert string from '2k3b' to 'kkbbb'"""
res = []
num = 0
letter = ''
for char in mess:
mess.split()
if char.isdigit():
num = int(char)
else:
num = 0
res.append(num * '%c' % letter)
return ''.join(res)
The decoder is not finished it's just were I stopped because I couldn't "see" what I was supposed to do. I usually write pseudo-code for all assigments and I did so for both the encoder and decoder but for some reason the decoder isn't getting through to me. I believe that I just lost my trail of thought but I could really use some guidance on this one. I'm reluctant to ask my teacher because he will just show me his code and I won't learn anything from that.
You are almost there. Below is your approach but with few minor changes.
Test: