Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Run-length encoding giving wrong result

I implemented a Run-length encoding that iterates through the input string, counting consecutive occurrences of each character. When the character changes, it appends the count followed by the character to the encoded string.

def run_length_encode(string):
    encoded = ""
    count = 1
    for i in range(1, len(string)):
        if string[i] == string[i - 1]:
            count += 1
        else:
            encoded += str(count) + string[i - 1]
            count = 1
    return encoded


# Example usage:
original_string = "AAAABBBCCDAA"
encoded_string = run_length_encode(original_string)

print("Original string:", original_string)
print("Encoded string:", encoded_string)

The issue is that the code I implemented does not count the last charater.
The above code return 4A3B2C1D instead of 4A3B2C1D2A.
Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

before returning encoded you need to append the count and character when the loop terminates encoded += str(count) + string[-1]

def run_length_encode(string):
    encoded = ""
    count = 1
    for i in range(1, len(string)):
        if string[i] == string[i - 1]:
            count += 1
        else:
            encoded += str(count) + string[i - 1]
            count = 1
    encoded += str(count) + string[-1]
    return encoded


# Example usage:
original_string = "AAAABBBCCDAA"
encoded_string = run_length_encode(original_string)

print("Original string:", original_string)
print("Encoded string:", encoded_string)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading