pythonrun-length-encoding

run length encoding for customized word


I am trying to make run length encoding for deferent result (RLE is counting letter/character, but I want to count modified/customize word).

def encode(message):
    count = 0
    chatacter = ''
    previous_char = message[0]
    result = ''
    length = len(message)

    i = 0
    while (i != length):
        chatacter = message[i]

        if previous_char == chatacter:
            count = count + 1
        else:
            result = result + str(count) + previous_char
            count = 1

        previous_char = chatacter
        i = i + 1

    return result + str(count) + str(previous_char)


encoded_message = encode("abaabaabaabaaabaaabaaabaaabaabababababababababaabaababaaaabaaaabaaaaaabaaaaaaaabaaaaaab")
print(encoded_message)

Result is

1a1b2a1b2a1b2a1b3a1b3a1b3a1b3a1b2a1b1a1b1a1b1a1b1a1b1a1b1a1b1a1b1a1b2a1b2a1b1a1b4a1b4a1b6a1b8a1b6a1b

My required result

ab1aab3aaab4aab1ab8aab2ab2aaaab2aaaaaab2aaaaaaaab2aaaaaab2

Can someone help me with this task?


Solution

  • In your code, the count variable was not cleared. There was also an incorrect combination of the encoded message at the end. Because of this, the last sequence was not added to the result. Instead, you can use a for loop. This usually ships to avoid indexing errors.

    def encode(message):
    count = 1
    result = ''
    for i in range(1, len(message)):
        if message[i] == message[i-1]:
            count += 1
        else:
            result += message[i-1] + str(count)
            count = 1
    
    return (result += message[-1] + str(count))