compression - Create a compress function in Python? -
i need create function called compress compresses string replacing repeated letters letter , number. function should return shortened version of string. i've been able count first character not others.
ex:
>>> compress("ddaaaff") 'd2a3f2' def compress(s): count=0 in range(0,len(s)): if s[i] == s[i-1]: count += 1 c = s.count(s[i]) return str(s[i]) + str(c)
here short python implementation of compression function:
def compress(string): res = "" count = 1 #add in first character res += string[0] #iterate through loop, skipping last 1 in range(len(string)-1): if(string[i] == string[i+1]): count+=1 else: if(count > 1): #ignore if no repeats res += str(count) res += string[i+1] count = 1 #print last 1 if(count > 1): res += str(count) return res
here few examples:
>>> compress("ddaaaff") 'd2a3f2' >>> compress("daaaafffyy") 'da4f3y2' >>> compress("mississippi") 'mis2is2ip2i'
Comments
Post a Comment