Skip to content

Commit 81fbcf4

Browse files
committed
completed 1.6
1 parent 36eb238 commit 81fbcf4

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed
Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
1-
""" 1.6 String Compression: Implement a method to perform basic string compression using hte counts of repeated characters. For example, the string 'aabcccccaaa' would become 'a2b1c5a3'. 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). """
2-
3-
4-
1+
""" 1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string 'aabcccccaaa' would become 'a2b1c5a3'. 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). """
52

3+
def compress(strng):
4+
compressed = ""
5+
curr_char = strng[0]
6+
curr_count = 1
7+
for i in xrange(1, len(strng)):
8+
if strng[i] == curr_char:
9+
curr_count += 1
10+
else:
11+
compressed += curr_char
12+
compressed += str(curr_count)
13+
curr_char = strng[i]
14+
curr_count = 1
15+
compressed += curr_char
16+
compressed += str(curr_count)
17+
return compressed
618

19+
# runtime is O(n) where n is the length of the string
20+
# make sure to clarify whether capital and lowercase letters count as the same or different (if same, add .lower() or .upper() method where necessary)
721

822

923
if __name__ == "__main__":
10-
print "nothing yet"
24+
print "TEST compress('aabcccccaaa') -> 'a2b1c5a3'"
25+
print compress('aabcccccaaa')

0 commit comments

Comments
 (0)