Create a compress function in Python?

后端 未结 19 1030
感动是毒
感动是毒 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:12

    I wanted to do it by partitioning the string. So aabbcc would become: ['aa', 'bb', 'cc']

    This is how I did it:

    def compression(string):
    
        # Creating a partitioned list
        alist = list(string)
        master = []
        n = len(alist)
    
        for i in range(n):
            if alist[i] == alist[i-1]:
                master[-1] += alist[i]
            else:
                master += alist[i]
    
    
        # Adding the partitions together in a new string
        newString = "" 
        for i in master:
            newString += i[0] + str(len(i))
    
        # If the newString is longer than the old string, return old string (you've not 
        # compressed it in length)
        if len(newString) > n:
            return string
        return newString
    
    
    
    string = 'aabbcc'
    print(compression(string))
    

提交回复
热议问题