Created
August 10, 2016 04:07
-
-
Save dudepare/ccdeda1be2788c9b8e9f1edb6559d1e0 to your computer and use it in GitHub Desktop.
String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase an…
This file contains hidden or 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
""" | |
String Compression: Implement a method to perform basic string | |
compression using the counts of repeated characters. For example, | |
the string aabcccccaaa would become a2blc5a3. If the "compressed" | |
string would not become smaller than the original string, your | |
method should return the original string. You can assume the | |
string has only uppercase and lowercase letters (a -z). | |
""" | |
def compress(inputstr): | |
if len(inputstr) == 0: | |
return "" | |
prev = inputstr[0] | |
count = 0 | |
compressed = [] | |
for c in inputstr: | |
if prev == c: | |
count += 1 | |
else: | |
compressed.append(prev) | |
compressed.append(str(count)) | |
count = 1 | |
prev = c | |
compressed.append(prev) | |
compressed.append(str(count)) | |
output = "".join(compressed) | |
if len(output) > len(inputstr): | |
return inputstr | |
else: | |
return output | |
import unittest | |
class TestCompress(unittest.TestCase): | |
def test_sample_case(self): | |
self.assertEqual(compress("aabcccccaaa"), "a2b1c5a3") | |
def test_empty(self): | |
self.assertEqual(compress(""), "") | |
def test_one(self): | |
self.assertEqual(compress("a"), "a") | |
def test_no_compression(self): | |
self.assertEqual(compress("abcdefghijklmnop"), "abcdefghijklmnop") | |
def test_front_compress(self): | |
self.assertEqual(compress("aaaaabc"), "a5b1c1") | |
def test_mid_compress(self): | |
self.assertEqual(compress("abbbbbbbbc"), "a1b8c1") | |
def test_end_compress(self): | |
self.assertEqual(compress("abccccc"), "a1b1c5") | |
def test_equal_length(self): | |
self.assertEqual(compress("aabb"), "a2b2") | |
def test_output_is_longer(self): | |
self.assertEqual(compress("aabcdefghijklmnop"), "aabcdefghijklmnop") | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Before arriving to this solution, it was coded and tested using pencil and paper first.