我正在尝试制作一个不使用 1s 的运行长度解码器。例如,可以传递的字符串类似于 ''' A2C3GTA'''。我做了我认为可行的事情,但很难找到我出错的地方。我是python的初学者,所以我很抱歉这个简单的问题。谢谢!
def decode(compressed):
decoded= ""
count = 0
for x in compressed :
if x.isdigit():
count += int(x)
y = compressed
decoded += y[int(x)+1] * count
count = 0
else :
decoded += x
print (decoded)
答案 0 :(得分:0)
当您找到数字-字母对时,展开该对后无法跳过该字母。这是因为您使用了 for
循环,这是一个比您的逻辑想要的更具限制性的结构。相反,请尝试:
idx = 0
while idx < len(compressed):
char = compressed[idx]
if char.isdigit():
# replicate next character
idx += 2
else:
decoded += char
idx += 1
这将处理您的迭代。
您在适当的复制中,输出中的 22
,这来自对位置的错误引用:
decoded += y[int(x)+1] * count
这里,x
是运行长度,不是字符的位置。如果输入是 A7B
,这个格式错误的表达式会因为索引越界而出错。
在我上面给你的代码中,只需继续使用 idx
作为索引。
我相信你可以从这里完成。