Created
November 16, 2013 00:31
-
-
Save catermelon/7494177 to your computer and use it in GitHub Desktop.
You have a string with many consecutive letters: "aabbaadddc". Write a function that compresses the string by counting the consecutive letters. (If there is only one letter, it should resolve to itself). "aaaaabbaadddc" -> "a5b2a2d3c"
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
#"aabbbcccdde" => "a2b3c3d2e1" | |
def encode_string(unencoded): | |
if unencoded is None or unencoded == "": | |
return None | |
last_letter = None | |
count = 0 | |
result = "" | |
for letter in unencoded: | |
if last_letter is None: | |
last_letter = letter | |
count = 1 | |
continue | |
if letter == last_letter: | |
count += 1 | |
else: | |
if count == 1: | |
result += last_letter | |
else: | |
result += "{0}{1}".format(last_letter, count) | |
last_letter = letter | |
count = 1 | |
if count == 1: | |
result += last_letter | |
else: | |
result += "{0}{1}".format(last_letter, count) | |
return result | |
def decode_string(encoded): | |
result = "" | |
numbers = [str(i) for i in range(1, 10)] | |
i = 0 | |
while i < len(encoded): | |
letter = encoded[i] | |
try: | |
count = encoded[i+1] | |
except IndexError: | |
count = None | |
if count and count in numbers: | |
result += letter * int(count) | |
i += 2 | |
else: | |
result += letter | |
i += 1 | |
return result | |
print encode_string("aabbbcccdd") | |
print encode_string("xyz") | |
print encode_string("aabbbcccdde") | |
assert encode_string("aabbbcccdde") == "a2b3c3d2e" | |
print decode_string("a2b3c3d2e") | |
print decode_string("ab3cz3d2e") | |
print decode_string("xyz") | |
assert "aabbbcccdde" == decode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment