-4

Need to write a python function which performs the run length encoding for a given string and returns the run length encoded String.

Went through various posts in Stack Overflow and other websites in Google to get a proper understanding in Run Length Encoding in Python. Tried coding and got some output but it doesn't match the specified output. I have stated my code and output below:

def encode(input_string):
    characters = []
    result = ''
    for character in input_string:
        # End loop if all characters were counted
        if set(characters) == set(input_string):
            break
        if character not in characters:
            characters.append(character)
            count = input_string.count(character)
            result += character
            if count > 1:
                result += str(count)
    return result

#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)

For the above string, I am getting the output as : A2B5C8

But the expected output is :1A4B8C1A1B

It would be really great if someone tell me where to make changes in the code to get the expected format of output.

  • `input_string.count(character)` counts how many instances of `character` are in the entire string, which is why your counts are off. The counts and character values are in the wrong order because that's the order in which you add them to the result. – cco Dec 21 '18 at 20:43

1 Answers1

1

You can use the following function to get the desired output:

string = "ABBBBCCCCCCCCAB"

def encode(string):
    counter = 1
    result = ""
    previousLetter = string[0]
    if len(string)==1:
      return str(1) + string[0]
    for i in range(1,len(string),1):
        if not string[i] == previousLetter:
            result += str(counter) + string[i-1]
            previousLetter = string[i]
            counter = 1

        else:
            counter += 1
        if i == len(string)-1:
                result += str(counter) + string[i]

    return result

result = encode(string)
print(result)

Output:

1A4B8C1A1B
Hakan
  • 13
  • 4
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29