Create a compress function in Python?

后端 未结 19 1197
感动是毒
感动是毒 2021-01-05 03:37

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 vers

19条回答
  •  时光取名叫无心
    2021-01-05 04:30

    Here is a short python implementation of a compression function:

    #d=compress('xxcccdex')
    #print(d)
    
    def compress(word):
        list1=[]
        for i in range(len(word)):
            list1.append(word[i].lower())
        num=0
        dict1={}
        for i in range(len(list1)):
            if(list1[i] in list(dict1.keys())):
                dict1[list1[i]]=dict1[list1[i]]+1
            else:
                dict1[list1[i]]=1
    
        s=list(dict1.keys())
        v=list(dict1.values())
        word=''
        for i in range(len(s)):
            word=word+s[i]+str(v[i])
        return word
    

提交回复
热议问题