File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ String Compression: Implement a method to perform basic string compression using the counts
3
+ of repeated characters. For example, the string aabcccccaaa would become a2blc5a3, If the
4
+ "compressed" string would not become smaller than the original string, your method should return
5
+ the original string. You can assume the string has only uppercase and lowercase letters (a - z).
6
+ Hints: #92, if 110
7
+
8
+ '''
9
+
10
+ from tokenize import String
11
+
12
+
13
+ def Str_compress (s ):
14
+ comp_str = ""
15
+ count_char = 1
16
+ for i in range (len (s )): #if i is greater than zero
17
+ if (i > 0 and s [i ] == s [i - 1 ]):
18
+ count_char += 1
19
+ elif (i > 0 and s [i ] != s [i - 1 ]):
20
+ comp_str += s [i - 1 ] + str (count_char )
21
+ count_char = 1
22
+
23
+ final_str = comp_str + s [- 1 ] + str (count_char ) #handling last char of string
24
+ if (len (final_str ) > len (s )):
25
+ return s
26
+ else :
27
+ return final_str
28
+
29
+ if __name__ == '__main__' :
30
+ s = input ("Enter string >> " ).strip ()
31
+ answer = Str_compress (s )
32
+ print (answer )
You can’t perform that action at this time.
0 commit comments