Perform length encoding in Python

Python Methods and Functions

For example, if the input string is "wwwwaaadexxxxxx", then the function should return "w4a3d1e1x6".

Examples:

 Input: str = 'wwwwaaadexxxxxx' Output:' w4a3d1e1x6' 

This problem has an existing solution, please refer to the link OrderedDict . The approach is very simple: first we create an ordered dictionary that contains the characters of the input string as the key and 0 as the default, now we run a loop to count the frequency of each character and map it to the corresponding key.

# Python code for encoding the length of the run

from collections import OrderedDict

def runLengthEncoding ( input ):

 

# Create an ordered dictionary of all bottom

# case alphabet so, its output will be

# dict = {& # 39; w & # 39 ;: 0, & # 39; a & # 39 ;: 0, & # 39; d & # 39 ;: 0, & # 39; e & # 39 ;: 0, & # 39; x & # 39 ;: 0}

dict = OrderedDict.fromkeys ( input , 0 )

 

# Now iterate over the input line to calculate

# frequency of each character, its output will be

# dict = {& # 39; w & # 39 ;: 4, & # 39; a & # 39 ;: 3, & # 39; d & # 39 ;: 1, & # 39; e & # 39 ;: 1, & # 39; x & # 39 ;: 6}

for ch in input :

dict [ch] + = 1

 

# now iterate over the dictionary to make

# output string of (key, value) pairs

output = ''

for key, value in dict . iteritems ():

  output = output + key + str (value)

return output

 
# Driver function

if __ name__ = = "__ main__" :

  input = ' wwwwaaadexxxxxx'

print runLengthEncoding ( input )

Output:

 'w4a3d1e1x6' 

This article is courtesy of Shashank Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





Tutorials