Run Length Encoding (RLE) Program in Python

by

Posted on 21 December 2017

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.


If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts

Search
Adverstisement
Adverstisement