Skip to content

Instantly share code, notes, and snippets.

@FranciscoCanas
Created August 20, 2014 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FranciscoCanas/51d953f679298ce19090 to your computer and use it in GitHub Desktop.
Save FranciscoCanas/51d953f679298ce19090 to your computer and use it in GitHub Desktop.
Run Length Encoding
def encode(input):
"""
Returns the Run Length Encoding for an input string.
"""
if not input:
return ''
result = []
count = 1
prev = input[0]
for char in input[1:]:
if char != prev:
result.append(str(count) + prev)
count = 1
prev = char
else:
count += 1
result.append(str(count) + prev)
return ''.join(result)
def assertEqual(expected, actual):
"""
Basic equality assertion. Prints PASS or FAIL.
"""
result = 'FAIL'
if expected == actual:
result = 'PASS'
print '{0}: {1} -> {2}'.format(result, expected, actual)
if __name__=="__main__":
tests = [
('',''),
('a', '1a'),
('aa', '2a'),
('aaab', '3a1b'),
('abc', '1a1b1c'),
('aaaaabbcaa', '5a2b1c2a'),
('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW','12W1B12W3B24W1B14W')
]
for test in tests:
assertEqual(encode(test[0]), test[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment