编辑:这似乎不仅仅是一个off-by-one错误。
我在下面的简单算法中得到了一个off-by-1错误,该算法应该显示字符串中的字母计数,沿着run-length encoding的行。
我可以理解为什么最后一个字符没有添加到结果字符串中,但是如果我增加i的range,我会得到index out of range,原因很明显。
我想知道从算法设计的角度来看,这里的概念问题是什么,以及如何让我的代码正常工作。
我是否需要一些特殊的代码来处理原始字符串中的最后一项?或者,将当前字符与previous字符进行比较可能更有意义,尽管这在算法开始时会带来问题?
对于这种算法,有没有一种通用的方法,将当前元素与前一个/下一个元素进行比较,从而避免索引超出范围的问题?
def encode(text):
# stores output string
encoding = ""
i = 0
while i < len(text) - 1:
# count occurrences of character at index i
count = 1
while text[i] == text[i + 1]:
count += 1
i += 1
# append current character and its count to the result
encoding += text[i] + str(count)
i += 1
return encoding
text = "Hello World"
print(encode(text))
# Gives H1e1l2o1 1W1o1r1l1发布于 2019-11-05 00:48:20
您说得对,如果最后一个字符与前一个字符不同(在本例中为d),那么您应该为外部循环设置while i < len(text)来处理最后一个字符。
然后,您的算法在全局范围内是正常的,但是在查找最后一个字符的匹配项时,它将崩溃。在这一点上,text[i+1]变得非法。
要解决这个问题,只需在内部循环中添加一个安全检查:while i+1 < len(text)
def encode(text):
# stores output string
encoding = ""
i = 0
while i < len(text):
# count occurrences of character at index i
count = 1
# FIX: check that we did not reach the end of the string
# while looking for occurences
while i+1 < len(text) and text[i] == text[i + 1]:
count += 1
i += 1
# append current character and its count to the result
encoding += text[i] + str(count)
i += 1
return encoding
text = "Hello World"
print(encode(text))
# Gives H1e1l2o1 1W1o1r1l1d1发布于 2019-11-05 01:28:43
如果你坚持你的策略,你将不得不检查i+1 < len(text)。这给出了类似的结果:
def encode(text):
L = len(text)
start = 0
encoding = ''
while start < L:
c = text[start]
stop = start + 1
while stop < L and text[stop] == c:
stop += 1
encoding += c + str(stop - start)
start = stop
return encoding做事情的另一种方法是记住每次运行的开始:
def encode2(text):
start = 0
encoding = ''
for i,c in enumerate(text):
if c != text[start]:
encoding += text[start] + str(i-start)
start = i
if text:
encoding += text[start] + str(len(text)-start)
return encoding这允许您只枚举输入,这感觉更像pythonic。
https://stackoverflow.com/questions/58696676
复制相似问题