I have a problem decoding.
First the string '44444'
get encoded to '54'
. (5 times 4)
Now when I want to decode '54'
its empty.
(It does function with letters)
The algorithm decodes the string '4a3b2c'
to 'aaaabbbcc'
.
Now when I want to decode '4a54'
it just gives 'aaaa'
but the right decoding is 'aaaa44444'
. How can I decode this?
Here is the code:
def decode_RLE(x):
decode = ''
count = ''
for i in x:
if i.isdigit():
#append to count
count += i
else i:
decode += i * int(count)
count = ''
return decode
You can try string multiplication:
def decode(string):
output = ''
for i in range(0, len(string), 2):
output += int(string[i]) * string[i + 1]
return output
print(decode("54"))
print(decode("4a54"))
Output:
44444
aaaa44444
You can even use a list comprehension:
def decode(s):
return ''.join(int(s[i]) * s[i + 1] for i in range(0, len(s), 2))