Skip to content Skip to sidebar Skip to footer

Python Compression Run Length Encoding

I am trying to learn about run length encoding and I found this challenge online that I cant do. It requires you to write a compression function called compression(strg) that takes

Solution 1:

This is an example of a longest repeated substring problem. It is classically solved with a suffix tree data structure.

For short strings, you can use a form of a regex:

import re

s1='1010101001010101101010100101010110101010010101011010101001010101'

i=2
l=s1
j=len(l)/2while i<len(s1):
    m=re.search('^(.{'+str(j)+'})\\1$',l)
    if m:
        l=m.group(1)
        i,j=i+1,len(l)/2continueelse:
        print'{0} * {1} = {2}'.format(l,i,s1)
        break

Prints your output. Note this only works for strings that have complete symmetry from the middle -- a small subset of this type of problem. To compress other types of strings, you would need a representational grammar of how the replaced elements are being substituted.

Solution 2:

Answer of this question with detail explanation are given in the following link:

Image compression by def compress(S) function using run-length codig

Hope it will clear your understanding of run length encoding of string and binary compression. This coding is done without using importing any re and itertools.

Post a Comment for "Python Compression Run Length Encoding"