RUN LENGTH ENCODING.
Given a string containing uppercase characters (A-Z), compress the string using Run Length encoding. Repetition of character has to be replaced by storing the length of that run.
Write a python function which performs the run length encoding for a given String and returns the run length encoded String.
Provide different String values and test your program
Sample Input |
Expected Output |
AAAABBBBCCCCCCCC |
4A4B8C |
AABCCA |
2A1B2C1A |
CODE :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def encode(message): | |
#logic | |
i=0 | |
count=1 | |
encoded_message="" | |
while(i<len(message)-1): | |
ch=message[i] | |
if (message[i]==message[i+1]): | |
count=count+1 | |
i=i+1 | |
else: | |
encoded_message=encoded_message+str(count)+ch | |
i=i+1 | |
count=1 | |
ch=message[i] | |
encoded_message=encoded_message+str(count)+ch | |
return encoded_message | |
encoded_message=encode("ABBCCCD") | |
print(encoded_message) |
0 Comments