Skip to content

Instantly share code, notes, and snippets.

@neotrinity
Created November 21, 2014 14:10
Show Gist options
  • Save neotrinity/01a02617870a9668424b to your computer and use it in GitHub Desktop.
Save neotrinity/01a02617870a9668424b to your computer and use it in GitHub Desktop.
Simple run length encoding problem
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