Created
August 20, 2014 15:22
-
-
Save FranciscoCanas/51d953f679298ce19090 to your computer and use it in GitHub Desktop.
Run Length Encoding
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 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