Run Length Encoding in Python
Last Updated :
21 Jul, 2022
Given an input string, write a function that returns the Run Length Encoded string for the input string. For example, if the input string is ‘wwwwaaadexxxxxx’, then the function should return ‘w4a3d1e1x6’.
Examples:
Input : str = 'wwwwaaadexxxxxx'
Output : 'w4a3d1e1x6'
This problem has existing solution please refer Run Length Encoding link. Here we will solve this problem quickly in python using OrderedDict. Approach is very simple, first we create a ordered dictionary which contains characters of input string as key and 0 as their default value, now we run a loop to count frequency of each character and will map it to it’s corresponding key.
Implementation:
Python3
<div id = "highlighter_850800" class = "syntaxhighlighter nogutter " ><table border = "0" cellpadding = "0" cellspacing = "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" >
|
Another code:
Python3
def encode(message):
encoded_message = ""
i = 0
while (i < = len (message) - 1 ):
count = 1
ch = message[i]
j = i
while (j < len (message) - 1 ):
if (message[j] = = message[j + 1 ]):
count = count + 1
j = j + 1
else :
break
encoded_message = encoded_message + str (count) + ch
i = j + 1
return encoded_message
encoded_message = encode( "ABBBBCCCCCCCCAB" )
print (encoded_message)
|
Please Login to comment...