gpt4 book ai didi

python 文本编码程序

转载 作者:行者123 更新时间:2023-12-01 01:50:06 25 4
gpt4 key购买 nike

将文本输入到定义 run_length_encoder 时,应压缩重复字母例如,当输入 aaabbac 时,输出应为 ['a','a',3,'b','b',2,'a','c']但我的代码没有压缩。

def run_length_encoder(string):
#def compress(string):

res = []

count = 1

#Add in first character
res.append(string[0])

#Iterate through loop, skipping last one
for i in range(len(string)-1):
if(string[i] == string[i+1]):
count+=1
res.append(string[i+1])
else:
if(count > 1):
#Ignore if no repeats
res.append(count)
res.append(string[i+1])
count = 1
#print last one
if(count > 1):
res.append(str(count))
return res

例如,当输入 abbbbaa 时,输出应该是这个 ['a', 'b', 'b', 4, 'a', 'a', 2] 而我得到的是这个 ['a ', 'b', 'b', 'b', 'b', 4, 'a', 'a', '2']

最佳答案

你也可以这样做:

def run_length_encoder(str_):
compressedString = ''
countConsecutive = 0
strLen = len(str_)
for i in range(strLen):
countConsecutive += 1
if i + 1 >= strLen or str_[i] != str_[i + 1]:
compressedString += '' + str_[i] + str(countConsecutive)
countConsecutive = 0

return compressedString

sample = 'aaabbac'
result = list(run_length_encoder(sample))
print(result)

关于python 文本编码程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com