Python,如何在列表末尾不需要额外的空间?

我编写了一个可以压缩字符序列的程序。


def compress(string):

    output = ""

    counter = 1

    firstLoop = True


    for element in range(0, len(string)):

        # if statement checking if current character was last character

        if string[element] == string[element - 1]:

            # if it was, then the character has been written more than one

            # time in a row, so increase counter

            counter = counter + 1

        else:

            # when we detect a new character reset the counter

            # and also record the character and how many times it was repeated

            if not firstLoop:

                output = output + string[element - 1] + str(counter)

        counter = 1


        firstLoop = False

    return output


data = "aaaabbbchhtttttttf"

print(data)


compressedData = compress(data)

print(compressedData)

程序输出:


aaaabbbchhtttttttf

a4b3c1h2t7

因此,它发现 'a' 有 '4' 个条目,所以它写入 'a4',然后为 b 的三个条目写入 'b3'。


问题是它忘记了字符串末尾的“f1”。我知道这是因为这条线:


output = output + string[element - 1] + str(counter)

由于 string[element-1] 指的是字符串中当前元素之前的位置,因此,它永远不会到达 'f' 所在的最终位置。如果没有“-1”,程序将无法运行,因为它没有写出正确的字母。


我怎样才能解决这个问题并使它能够包含 f?


正确的输出应该是 a4b3c1h2t7f1。


谢谢 :)


编辑:我忘了提到如果我在 'f' 后面包含一个额外的字符,例如只是一个空格,程序就可以工作。但这当然是因为我的字符串中的最后一个字符只是一个空格而不是一个字母。


守着一只汪
浏览 139回答 3
3回答

炎炎设计

你可以让它更简单并在最后添加一个字符:def compress(string):    output = ""    counter = 0    string = string + '|'    for element in range(0, len(string)):        # if statement checking if current character was last character        if string[element] == string[element - 1]:            # if it was, then the character has been written more than one            # time in a row, so increase counter            counter = counter + 1        elif element != len(string):            output = output + string[element - 1] + str(counter)            counter = 1    return output[2:]data = "aaaabbbchhtttttttf"print(data)compressedData = compress(data)print(compressedData)

白衣染霜花

def compress(string):output = ""counter = 1for element in range(1, len(string)):    # if statement checking if current character was last character    if string[element] == string[element - 1]:        # if it was, then the character has been written more than one        # time in a row, so increase counter        counter = counter + 1    else:        # when we detect a new character reset the counter        # and also record the character and how many times it was repeated        output = output + string[element - 1] + str(counter)        counter = 1return output + string[-1] + str(counter)另外请注意,你需要开始计数形式1不0和摆脱firstLoop
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python