Skip to content

Instantly share code, notes, and snippets.

@yokiy
Last active August 29, 2015 14:02
Show Gist options
  • Save yokiy/8dcfbd745317c5c9b46e to your computer and use it in GitHub Desktop.
Save yokiy/8dcfbd745317c5c9b46e to your computer and use it in GitHub Desktop.
CC 1.5
# 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)
@nealhu
Copy link

nealhu commented Jun 21, 2014

Please try some test cases e.g. "" and "abbcdddddd"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment