I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. My function should return the shortened version of the string. I’ve been able to count the first character but not any others.
Ex:
JavaScript
x
14
14
1
>>> compress("ddaaaff")
2
'd2a3f2'
3
4
5
def compress(s):
6
count=0
7
8
for i in range(0,len(s)):
9
if s[i] == s[i-1]:
10
count += 1
11
c = s.count(s[i])
12
13
return str(s[i]) + str(c)
14
Advertisement
Answer
Here is a short python implementation of a compression function:
JavaScript
1
24
24
1
def compress(string):
2
3
res = ""
4
5
count = 1
6
7
#Add in first character
8
res += string[0]
9
10
#Iterate through loop, skipping last one
11
for i in range(len(string)-1):
12
if(string[i] == string[i+1]):
13
count+=1
14
else:
15
if(count > 1):
16
#Ignore if no repeats
17
res += str(count)
18
res += string[i+1]
19
count = 1
20
#print last one
21
if(count > 1):
22
res += str(count)
23
return res
24
Here are a few examples:
JavaScript
1
7
1
>>> compress("ddaaaff")
2
'd2a3f2'
3
>>> compress("daaaafffyy")
4
'da4f3y2'
5
>>> compress("mississippi")
6
'mis2is2ip2i'
7