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
>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)