Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
question from:https://stackoverflow.com/questions/65946527/decode-digits-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
91 views
Welcome To Ask or Share your Answers For Others

1 Answer

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...