Skip to content

Instantly share code, notes, and snippets.

@rchacon
Created December 20, 2014 04:14
Show Gist options
  • Save rchacon/4be09edaaceb360717c6 to your computer and use it in GitHub Desktop.
Save rchacon/4be09edaaceb360717c6 to your computer and use it in GitHub Desktop.
Count occurrences of letters in string.
"""
hhhhh aaaaa => h5 5a5
"""
def compress_sentence(sentence):
prev_letter = sentence[0]
frequency = 1
output = ''
for letter in sentence[1:]:
if prev_letter == letter:
frequency += 1
else:
output += '%s%s' % (prev_letter, frequency)
frequency = 1
prev_letter = letter
output += '%s%s' % (letter, frequency)
if len(output) < len(sentence):
return output
return sentence
sentence = raw_input("")
print compress_sentence(sentence)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment