首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RLE算法中避免Python Off-by-One错误

RLE算法中避免Python Off-by-One错误
EN

Stack Overflow用户
提问于 2019-11-04 23:41:36
回答 2查看 115关注 0票数 1

编辑:这似乎不仅仅是一个off-by-one错误。

我在下面的简单算法中得到了一个off-by-1错误,该算法应该显示字符串中的字母计数,沿着run-length encoding的行。

我可以理解为什么最后一个字符没有添加到结果字符串中,但是如果我增加irange,我会得到index out of range,原因很明显。

我想知道从算法设计的角度来看,这里的概念问题是什么,以及如何让我的代码正常工作。

我是否需要一些特殊的代码来处理原始字符串中的最后一项?或者,将当前字符与previous字符进行比较可能更有意义,尽管这在算法开始时会带来问题?

对于这种算法,有没有一种通用的方法,将当前元素与前一个/下一个元素进行比较,从而避免索引超出范围的问题?

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-05 00:48:20

您说得对,如果最后一个字符与前一个字符不同(在本例中为d),那么您应该为外部循环设置while i < len(text)来处理最后一个字符。

然后,您的算法在全局范围内是正常的,但是在查找最后一个字符的匹配项时,它将崩溃。在这一点上,text[i+1]变得非法。

要解决这个问题,只需在内部循环中添加一个安全检查:while i+1 < len(text)

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2019-11-05 01:28:43

如果你坚持你的策略,你将不得不检查i+1 < len(text)。这给出了类似的结果:

代码语言:javascript
复制
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

做事情的另一种方法是记住每次运行的开始:

代码语言:javascript
复制
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。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58696676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档