File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 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 ))
You can’t perform that action at this time.
0 commit comments