-2

I need to write a program which would take an alphanumeric string as input. The string would contain only lower case characters and number from 0 to 9.

I have to compress the alphabets as alphabets multiplied by number of times continous repetition, like:

  • aaa to a3
  • bbbb to b4
  • c to c1

If there are any integers in the input string, then I have to add the integers.

Return the compressed string multiplied by added integers.

def std(string):
    res =" "
    con =1
    res += string[0]
    for i in range((len(string)-1)):
        if (string[i] == string[i+1]):
            con+=1
        else:
            if (con>1):
                res += str(con)
                res+=string[i+1]
                con =1
            if (con>1):
                res+= str(con)
            return res

print(std('aabbb3cccc2d'))

I wrote this program and got the output a2b.

The expected output is a2b3c4d1a2b3c4d1a2b3c4d1a2b3c4d1a2b3c4d1. Could anyone tell me where am I going wrong?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Does this answer your question? [Function doesn't return all results from 'for' loop](https://stackoverflow.com/questions/16103187/function-doesnt-return-all-results-from-for-loop) – mkrieger1 Jun 17 '20 at 16:35

1 Answers1

0

Multiple problems I believe you have in that function:

  • You return inside the loop and leave the function without iterating through the whole string

  • You only check if the next letter is equal and don't keep looking further

  • If you loop len(string) - 1 you never check the last character

  • You don't check if the character you're in is a digit or not so you can't keep track of how many times your string will be multiplied in the end

I have came across this solution since I couldn't correct yours, I hope it helps.

def std(string):
    multiplier = 0
    final_string = ""
    jumper = 0

    for i in range(len(string)):
        if jumper:
            jumper -= 1
            continue

        if string[i].isdigit():
            multiplier += int(string[i])
            continue    

        charMultiplier = 0
        for j in range(i + 1, len(string)):
            if(string[i] == string[j]):
                charMultiplier += 1                    
            else:
                break      

        final_string += string[i]       
        final_string += str(charMultiplier + 1)

        jumper += charMultiplier

    final_string = final_string * multiplier

    return final_string
walkman
  • 478
  • 1
  • 8
  • 21
  • Can you explain what you think the problem in the original code was, and how this problem is solved in the code you have shown? – mkrieger1 Jun 17 '20 at 16:33