Run Length Encoding (RLE) Program in Python

Run Length Encoding is a lossless data compression technique which converts repetitive chunks of data into single value and counts. This type of compression is suitable when data contains many such runs. RLE is mainly used in Graphics Interchange Format (GIF) files.

Consider a display containing continuous white pixel colours, RLE will encode them into a single value and count let us see a simple example.

Data: SSSSXXXXXRRRRRRRR

Encoded Data: S4X5R8

Now we will write python code to perform Run Length Encoding, first, we will create the encodeRLE() function.

def encodeRLE(encodeStr): encoded = "" count = 0 i = 0 character = encodeStr[i] for i in range(0,len(encodeStr)): if(encodeStr[i] == character): count += 1 else: encoded += (str(character)+""+str(count)) character = encodeStr[i] count = 1 if(i==(len(encodeStr)-1)): encoded += (str(character)+""+str(count)) return encoded 

In the above method, the encoded string will be stored in the “encoded” variable, “count” variable is used to count the number of occurrence of a particular value in a run and i is used for looping through the whole string.

In this python script we are going to pass the input as a command line argument for that we are going to use the pythons “argparse” module below is the code to setup the command line argument.

import argparse parser = argparse.ArgumentParser() parser.add_argument("string",type=str,help="Input String")  args = parser.parse_args()

Now let’s see the complete script for Run Length Encoding in Python.

import argparse  parser = argparse.ArgumentParser() parser.add_argument("string",type=str,help="Input String")  args = parser.parse_args()    def encodeRLE(encodeStr): encoded = "" count = 0 i = 0 character = encodeStr[i] for i in range(0,len(encodeStr)): if(encodeStr[i] == character): count += 1 else: encoded += (str(character)+""+str(count)) character = encodeStr[i] count = 1 if(i==(len(encodeStr)-1)): encoded += (str(character)+""+str(count)) return encoded   print("---------Encoded Version-----------") print(encodeRLE(args.string))

Output:

Run Length Encoding in python

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don’t forget to subscribe to our Newsletter. If you like this article, then please share it and help us grow.


Preorder and Postorder Traversal of binary tree in Python
02 September 2018

Binary Tree in Python
02 September 2018

Image Sharpening by High Pass Filter using Python and OpenCV
17 August 2018

Explaining Register variables in C with examples
17 August 2018

C program to generate all combinations of N-Bit Binary String
10 July 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Понравилась статья? Поделиться с друзьями:
Добавить комментарий