我写了一个可以压缩字符序列的程序。
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”之后添加一个额外的字符(例如空格),程序就可以运行。但这当然是因为我的字符串中的最后一个字符只是一个空格而不是一个字母。
最佳答案
您可以使用 itertools.groupby
完成这一切和 sum
并避免所有计数和跟踪索引:
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'
关于Python,如何在列表末尾不需要额外的空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52520457/