-3

I'm trying to make a run length decoder that doesn't use 1s. For example a string that could be passed through would be something like ''' A2C3GTA'''. I made what i thought would work and am having trouble finding where I went wrong. I'm a beginner to python so I am sorry for the simple question. Thank you!

def decode(compressed):
    decoded= ""
    count = 0

    for x in compressed :
        if x.isdigit():
            
            count += int(x)
            y = compressed
            decoded += y[int(x)+1] * count
            count = 0
        else :
            decoded += x
        
           
    print (decoded)  
808Blues
  • 87
  • 1
  • 4
  • 2
    Please provide the expected [MRE - Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Show where the intermediate results deviate from the ones you expect. We should be able to paste a single block of your code into file, run it, and reproduce your problem. This also lets us test any suggestions in your context. We also expect that you will trace the suspect values just before the point of error. Where are you confused about how they got to those values? – Prune Feb 18 '21 at 04:23

1 Answers1

0

When you find a number-letter pair, you fail to skip the letter after you expand the pair. This is because you used a for loop, which is a more restrictive structure than your logic wants. Instead, try:

idx = 0
while idx < len(compressed):
    char = compressed[idx]
    if char.isdigit():
        # replicate next character
        idx += 2
    else:
        decoded += char
        idx += 1

That will take care of your iteration.

Your in appropriate replication, the 22 in your output, this comes from an incorrect reference to the position:

        decoded += y[int(x)+1] * count

Here, x is the run length, not the position of the character. If the input were A7B, this ill-formed expression would fault because of an index out of bounds.

In the code I gave you above, simply continue to use idx as the index.

I trust you can finish from here.

Prune
  • 76,765
  • 14
  • 60
  • 81