python中的回文检查器,超出范围的索引解决方法

2024-03-29 00:33:05 发布

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

嗨,我试图使这个程序不使用反向或排序函数在Python3的工作。它只是用来检查回文。我遇到的问题是,每次运行索引时,索引都超出了范围。有办法解决这个问题吗?你知道吗

def is_palindrome(word):
    if len(word) <= 1:
        return True
    else:
        left = 0
        right = len(word) - 1
        while left < right:
            if word[left] == word[right]:
                left += 1
                right += 1
            else:
                return False
        return True

is_palindrome("mom")
is_palindrome("root")
is_palindrome("racecar")

Tags: 函数程序righttruelenreturnif排序
2条回答

你可以写得更简洁一点。你知道吗

>>> def is_palin(w):
...     return len(w) <= 1 or (w[0] == w[-1] and is_palin(w[1:-1]))              
... 
>>> is_palin("xax")
True
>>> is_palin("xaax")
True
>>> is_palin("xaab")
False

right += 1应该是right -= 1。你知道吗

相关问题 更多 >