Created
November 21, 2014 14:10
-
-
Save neotrinity/01a02617870a9668424b to your computer and use it in GitHub Desktop.
Simple run length encoding problem
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
def compress(s): | |
""" | |
s -> string to be compressed | |
retuns -> compressed string | |
""" | |
if not s: | |
return "" | |
prev = None | |
count = 0 | |
result = [] | |
for c in s: | |
if prev and prev != c: | |
result.append(prev) | |
result.append(str(count)) | |
count = 0 | |
count+=1 | |
prev = c | |
result.append(prev) | |
result.append(str(count)) | |
return "".join(result) | |
if __name__ == '__main__': | |
s = "AAABBCCDDDDEFFFFF" | |
print compress(s) | |
s = "" | |
print compress(s) | |
s = "ABCD" | |
print compress(s) | |
s = "A" | |
print compress(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment