String Compression in Python

Sometimes,It become very essential to Compress a code in python,In realworld context to find motifs in DNA sequences compressing them in a certain way is necessary.One such example is presented below

def compress_string(s):
  n=len(s)
  for size in range(1,n//2+1):
      if n%size==0:
          sub=s[:size]
          if sub*(n//size)==s:
             return f"{n//size}({sub})"
   return s
s="abcabcabcaba"
print(compress_string(s))

 

OUTPUT:

4(abc)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top