1

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'))
petezurich
  • 9,280
  • 9
  • 43
  • 57
Itay
  • 11
  • 2
  • Your problem is that to get the integer, you only check the very next character (`compressed_seq[i + 1]`) rather than getting the full number, so it sees `11` as just `1`. – Andrew McClement Jul 29 '22 at 10:44
  • How can I fix the problem, that it sees the 11 not 1 ? – Itay Jul 29 '22 at 10:46

1 Answers1

0

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

Andrew McClement
  • 1,171
  • 5
  • 14