当输入文本到定义运行长度编码器时,代表字母应该被压缩 例如, 输入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
例如,当输入abbbaa时,输出应该是['a','b','b',4','a','a',2],而我得到的是['a','b','b','b','4','a','a','2']
你的逻辑需要修正。固定编辑处理偶数和奇数结束情况。你知道吗
在弦上测试: string=“aaabbadddaad”输出:['a',3',b',2',a',2',d',3',a',2',d',1] string=“aaabbaddd”输出:['a',3',b',2',a',2',d',3] string=“aabccdd”输出:['a',2',b',1',c',2',d',2]
你也可以这样做:
Itertools爱你,希望你快乐:
相关问题 更多 >
编程相关推荐