Create a compress function in Python?

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

    Just another simplest way to perform this:

    def compress(str1):
        output = ''
        initial = str1[0]
        output = output + initial
        count = 1
        for item in str1[1:]:
            if item == initial:
                count = count + 1
            else:
                if count == 1:
                    count = ''
                output = output + str(count)
                count = 1
                initial = item
                output = output + item
        print (output)
    

    Which gives the output as required, examples:

    >> compress("aaaaaaaccffffddeehhyiiiuuo")
    a7c2d4e2h2yi3u2o
    
    >> compress("lllhhjuuuirrdtt")
    l3h2ju3ir2dt
    
    >> compress("mississippi")
    mis2is2ip2i
    
    0 讨论(0)
提交回复
热议问题