Skip to content

Commit 7c17bd3

Browse files
string compression solution
1 parent c709cc6 commit 7c17bd3

File tree

1 file changed

+49
-0
lines changed
  • Python/chapter01/1.6 - String Compression

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#!/usr/bin/python3
2+
import unittest
3+
4+
5+
def string_compression(string):
6+
'''Implement a method to perform basic string compression using the counts
7+
of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the
8+
"compressed" string would not become smaller than the original string, your method should return
9+
the original string. You can assume the string has only uppercase and lowercase letters (a - z). '''
10+
if not isinstance(string, str):
11+
return False
12+
13+
new_str = ''
14+
count, new_count = 0, 0
15+
for idx in range(len(string) - 1):
16+
count += 1
17+
if string[idx] is not string[idx + 1]:
18+
new_str += string[idx]
19+
new_str += str(count)
20+
count = 0
21+
if idx is len(string) - 2:
22+
if string[idx] is string[idx + 1]:
23+
new_str += string[idx]
24+
new_str += str(count + 1)
25+
else:
26+
new_str += string[idx + 1]
27+
new_str += '1'
28+
29+
for letter in new_str:
30+
if letter is '1':
31+
new_count += 1
32+
33+
if len(string) // new_count is 1:
34+
return string
35+
return new_str
36+
37+
38+
class Test(unittest.TestCase):
39+
def test1(self):
40+
self.assertEqual(string_compression('aabcccccaaa'), 'a2b1c5a3')
41+
self.assertEqual(
42+
string_compression('bbaaaabcdeeefff'),
43+
'b2a4b1c1d1e3f3')
44+
self.assertEqual(string_compression('abcdef'), 'abcdef')
45+
self.assertNotEqual(string_compression('abcdef'), 'a1b1c1d1e1f1')
46+
47+
48+
if __name__ == '__main__':
49+
unittest.main()

0 commit comments

Comments
 (0)