Home > Back-end >  Finding the run length encoding for characters works on most of the test cases except one
Finding the run length encoding for characters works on most of the test cases except one

Time:09-21

For multiple repeating character string my code is working fine, but here is the scenario where I give string "aaabba" the expected output is a3b2a1 but I get only a3b2. Please advise me as what is wrong in the code.

st = "aaabba"
n = len(st)
i = 0
while i < n - 1:
    count = 1   
    while (i < n-1 and st[i] == st[i 1]):
        count  = 1
        i  = 1
    i  = 1
    print(st[i - 1]   str(count), end="")

CodePudding user response:

The problem is in first while loop. The code should be:

st = "aaabba"
n = len(st)
i = 0
while i < n:
    count = 1   
    while (i < n-1 and st[i] == st[i 1]):
        count  = 1
        i  = 1
    i  = 1
    print(st[i - 1]   str(count), end="")
  • Related