Create a compress function in Python?

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

    This is a solution to the problem. But keep in mind that this method only effectively works if there's a lot of repetition, specifically if consecutive characters are repetitive. Otherwise, it will only worsen the situation.

    e.g.,
    AABCD --> A2B1C1D1
    BcDG ---> B1c1D1G1

    def compress_string(s):
        result = [""] * len(s)
        visited = None
    
        index = 0
        count = 1
    
        for c in s:
            if c == visited:
                count += 1
                result[index] = f"{c}{count}"
            else:
                count = 1
                index += 1
                result[index] = f"{c}{count}"
                visited = c
    
        return "".join(result)
    

提交回复
热议问题