Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,如何在列表末尾不需要额外的空间?_Python_Algorithm_List - Fatal编程技术网

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

Python,如何在列表末尾不需要额外的空间?,python,algorithm,list,Python,Algorithm,List,我写了一个程序,可以压缩一系列字符 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[eleme

我写了一个程序,可以压缩一系列字符

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',然后'b3'代表三个b条目

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

output = output + string[element - 1] + str(counter)
由于字符串[element-1]指的是当前元素之前字符串中的位置,因此,它永远不会到达“f”所在的最终位置。没有'-1'程序无法工作,因为它无法写入正确的字母

我怎样才能绕过这个问题,使它能够包含f

正确的输出应为a4b3c1h2t7f1

谢谢:)


编辑:我忘了提到,如果我在“f”后面加上一个额外的字符,比如一个空格,程序就可以运行。但这当然是因为我字符串中的最后一个字符只是一个空格而不是一个字母。

您可以使用并避免所有计数和跟踪索引:

from itertools import groupby

def compress(string):
    return ''.join(k + str(sum(1 for _ in g)) for k, g in groupby(string))

>>> compress("aaaabbbchhtttttttf")
'a4b3c1h2t7f1'

您可以使用和来完成这一切,并避免对索引进行计数和跟踪:

from itertools import groupby

def compress(string):
    return ''.join(k + str(sum(1 for _ in g)) for k, g in groupby(string))

>>> compress("aaaabbbchhtttttttf")
'a4b3c1h2t7f1'

尝试将范围(0,len(string)+1)中的元素的循环更改为
,并添加额外的if条件:

for element in range(0, len(string) + 1):
    if element == len(string):
        output = output + string[element-1] + str(counter)
    # if statement checking if current character was last character
    elif string[element] == string[element - 1]: ...

尝试将范围(0,len(string)+1)中的元素的循环更改为
,并添加额外的if条件:

for element in range(0, len(string) + 1):
    if element == len(string):
        output = output + string[element-1] + str(counter)
    # if statement checking if current character was last character
    elif string[element] == string[element - 1]: ...

您可以使其更简单,并在末尾添加一个字符:

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 = 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)
还请注意,您需要开始计算表单
1
而不是
0
,并去掉
firstLoop


还请注意,您需要开始计算表单
1
而不是
0
,并摆脱
firstLoop

,以修复代码的精神,您只需在更改时添加计数器之前先将元素添加到输出即可。您可以使用一个名为
else
的整洁处理,它将在末尾运行for循环,从而将最后一个计数器添加到
f
。无需缓冲或导入任何特殊内容,您已经非常接近:

def compress(string):
    output = ""
    counter = 0
    firstLoop = True

    for i in range(len(string)):
        # if statement checking if current character was last character
        if firstLoop:
            counter += 1
            output += string[i]
        else:
            if string[i] == string[i - 1]:
                counter += 1
            else:                
                output += str(counter) + string[i]
                counter = 1
        firstLoop = False      
    else:
        output += str(counter)
    return output

data = "aaaabbbchhtttttttf"
print(data)

compressedData = compress(data)
print(compressedData)

本着修复代码的精神,您只需要简单地将元素首先添加到输出,然后再添加更改计数器。您可以使用一个名为
else
的整洁处理,它将在末尾运行for循环,从而将最后一个计数器添加到
f
。无需缓冲或导入任何特殊内容,您已经非常接近:

def compress(string):
    output = ""
    counter = 0
    firstLoop = True

    for i in range(len(string)):
        # if statement checking if current character was last character
        if firstLoop:
            counter += 1
            output += string[i]
        else:
            if string[i] == string[i - 1]:
                counter += 1
            else:                
                output += str(counter) + string[i]
                counter = 1
        firstLoop = False      
    else:
        output += str(counter)
    return output

data = "aaaabbbchhtttttttf"
print(data)

compressedData = compress(data)
print(compressedData)

返回输出+字符串[-1]+str(计数器)。另外,您的计数器=1应该在elseThank中,谢谢!!这很有效。是的,它在else中,没有正确地复制和粘贴@juvianreturn输出+字符串[-1]+str(计数器)。另外,您的计数器=1应该在elseThank中,谢谢!!这很有效。是的,它在else中,没有正确复制和粘贴@juvianRunning speed tests,这比itertools解决方案略快,尽管我认为itertools解决方案是一种非常好的Python方式。是的,这是我以前的解决方案,感谢运行速度测试的帮助,这比itertools解决方案快一点,尽管我认为itertools解决方案是一种非常好的Python方式。是的,这是我以前的解决方案,谢谢你的帮助