我获取索引器错误:字符串索引超出范围

2024-10-02 14:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

def is_palindrome(x, pos_index, neg_index):
    if x[pos_index] == x[neg_index]:
        print("")
    else:
        return False

    pos_index += 1
    neg_index -= 1

    is_palindrome(x, pos_index, neg_index)


print(is_palindrome("racecar", 0, -1))

Tags: posfalseindexreturnifisdefelse
3条回答

出现错误的原因是is_palindrome()连续调用is_palindrome(),如果单词是回文,则不会停止。仅当单词不是回文时,函数才会返回。由于没有停止点,最终正索引和负索引都将超过字符串的最大索引。我会尝试使用这个:

def is_palindrome(phrase):
    phrase = "".join(phrase.lower().split())
    index, imax = 0, len(phrase)-1
    while index < imax-index:
        if phrase[index] != phrase[imax-index]:
            return False
        index += 1
    return True

请注意,这只会检查直到index尽可能接近字符串的中间位置(这可以通过将print(index)放入while循环中来观察)。这样,代码就不会“双重检查”字符串的后半部分

以下是一些测试运行:

>>> is_palindrome("racecar")
True
>>> is_palindrome("bus")
False
>>> is_palindrome("a man a plan a canal panama")
True
>>> is_palindrome("AABBAA")
True

但是,如果希望保留递归性质,可以尝试使用以下方法:

def is_palindrome(phrase, positive=0, negative=-1):
    phrase = ''.join(phrase.lower().split())
    if positive >= len(phrase):
        return True
    if phrase[positive] == phrase[negative]:
        return is_palindrome(phrase, positive+1, negative-1)
    return False

一些测试运行:

>>> is_palindrome("racecar")
True
>>> is_palindrome("bus")
False
>>> is_palindrome("A man a plan a canal panama")
True
>>> is_palindrome("AABBAA")
True

你的最终状态不见了。每次调用函数时,pos_索引变为6('r')。在此之后,您应该停止,但您可以添加一个,然后再次启动该函数。所以你得到了一个超出范围的字符串索引

还有一点注意,对于你的下一个问题,一些补充信息或一个特定的问题会很好

如果我要修复您的代码并保留大部分代码,我会执行以下操作:

def is_palindrome_recursive(x, pos_index, neg_index):
    if -neg_index >= len(x):
        return True

    if x[pos_index] != x[neg_index]:
        return False

    pos_index += 1
    neg_index -= 1

    return is_palindrome_recursive(x, pos_index, neg_index)

def is_palindrome(string):
    return is_palindrome_recursive(string, 0, -1)

print(is_palindrome("racecar"))

其中主要的变化是:当我们递归地将输入减少到一个字母或更少时,增加了一个return情况;处理递归调用的结果——一个常见的递归初学者错误

由于这不是一个固有的数学问题,我倾向于从解中得到数字和数学运算符。我还将把参数视为一个序列,而不是一个字符串,以允许在字符的strlist之间进行流畅的转换:

def is_palindrome(sequence):
    if sequence:
        first, *rest = sequence

        if rest:
            *middle, last = rest

            if first != last:
                return False

            return is_palindrome(middle)

    return True

if __name__ == "__main__":
    print(is_palindrome("racecar"))
    print(is_palindrome("radar"))
    print(is_palindrome("ABBA"))
    print(is_palindrome("pop"))
    print(is_palindrome("cc"))
    print(is_palindrome("I"))
    print(is_palindrome(""))

我希望这个问题的递归谓词函数有三种return可能性:return True成功^失败时{}return is_palindrome(...)一个递归,我还不知道

相关问题 更多 >