Last active
August 29, 2015 14:02
-
-
Save yokiy/8dcfbd745317c5c9b46e to your computer and use it in GitHub Desktop.
CC 1.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# cc1.5 Implement a method to perform string compression using counts of repeated characters. If the compressed string is not smaller than the ooriginal string, return the original one. | |
def compression(s): | |
list1 = list(s) | |
list2 = [] | |
c = 1 | |
j = 0 | |
for i in range(1, len(list1)): | |
if list1[i] == list1[j]: | |
c += 1 | |
else: | |
list2.append(list1[j]) | |
list2.append(str(c)) | |
c = 1 | |
j = i | |
#to append the last char in string | |
list2.append(list1[j]) | |
list2.append(str(c)) | |
cmpstring = ''.join(list2) | |
if len(cmpstring) >= len(s): | |
cmpstring = s | |
return cmpstring | |
s = raw_input('Input a string:') | |
print compression(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please try some test cases e.g. "" and "abbcdddddd"