Skip to content

Commit 8bb5ef5

Browse files
committed
working string compressions
1 parent 5ab9e73 commit 8bb5ef5

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

algorithms/string_compression.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/usr/bin/env python3
2+
"""Python solution for CtCI 6th Edition Problem 1.4
3+
4+
Implement a method to perform basic string compression using the counts of
5+
repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.
6+
If the "compressed" string would not become smaller than the original string,
7+
your method should return the original string. You can assume the string has
8+
only uppercase and lowercase letters (a - z).
9+
10+
>>> compress_string("aabcccccaaa")
11+
'a2b1c5a3'
12+
13+
>>> compress_string('aaaaaaaa')
14+
'a8'
15+
16+
Following examples would return strings that are shorter than or equal to the
17+
original string and just return the original string.
18+
>>> compress_string("aabbccaa")
19+
'aabbccaa'
20+
21+
>>> compress_string("aabcca")
22+
'aabcca'
23+
24+
>>> compress_string("abcde")
25+
'abcde'
26+
"""
27+
28+
29+
def compress_string(string):
30+
char_count = 1
31+
compressed_string = ""
32+
for pos, char in enumerate(string):
33+
if pos + 1 < len(string) and char == string[pos + 1]:
34+
char_count += 1
35+
else:
36+
compressed_chars = char + str(char_count)
37+
compressed_string = compressed_string + compressed_chars
38+
char_count = 1
39+
if len(compressed_string) < len(string):
40+
return compressed_string
41+
else:
42+
return string
43+
44+
if __name__ == "__main__":
45+
input_string = input("Enter string to compress: ")
46+
print(compress_string(input_string))

0 commit comments

Comments
 (0)