Skip to content
Advertisement

Run length decompression python [closed]

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)  

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement