String Compression

Q. Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the “compressed” string would not become smaller than the original string, your method should return the original string.

def compressed_string(str1):
    comp_string = ""
    count = 1
    last_char = str1[0]
    for iPtr in range(1, len(str1)):
        if str1[iPtr] == last_char:
            count += 1
            comp_string += last_char + str(count)
            last_char = str1[iPtr]
            count = 1
    comp_string += last_char + str(count)
    if len(comp_string) > len(str1):
        return "No need of compression"
        return comp_string

if __name__ == "__main__":
    print compressed_string("aabcccccaaa")
    print compressed_string("debanjan")


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s