Created
December 20, 2014 04:14
-
-
Save rchacon/4be09edaaceb360717c6 to your computer and use it in GitHub Desktop.
Count occurrences of letters in string.
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
""" | |
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