Itay
Itay

Reputation: 11

Run Length Decoding

I have a function for run length decoding in Python. It is working with single digit numbers, but if my number is above 9, it doesn't work. As you can see in my code, I want to print c 11 times, but it only prints it one time. How can I fix it ? I want to keep the code I have, without any special libraries. Example: Input is (A2B3C11) then output should be (AABBBCCCCCCCCCCC), but currently my output is only (AABBBC)

def run_length_decoding(compressed_seq):
seq = ''
for i in range(0, len(compressed_seq)):
    if compressed_seq[i].isalpha() == True:
        for j in range(int(compressed_seq[i + 1])):
            seq += compressed_seq[i]

return (seq) 
print(run_length_decoding('A2B3C11'))

Upvotes: 1

Views: 1400

Answers (1)

Andrew McClement
Andrew McClement

Reputation: 1418

I'll preface this answer by saying a regex would solve this pretty nicely.

Trying to keep relatively closely to your original code without importing any additional modules:

def run_length_decoding(compressed_seq: str) -> str:
    seq = ""
    current_letter = None
    for character in compressed_seq:
        if character.isalpha():
            if current_letter is not None:
                seq += current_letter * int(number)

            current_letter = character
            number = ""
        else:
            # We assume that this is the number following the letter.
            number += character

    if current_letter is not None:
        seq += current_letter * int(number)

    return seq

Try it at https://www.mycompiler.io/view/CVsq0tCieVP

Upvotes: 0

Related Questions