大纲
如果第 i 个字符与第 len-i 个字符相同,则短语是回文。由于该系列是镜像,因此您只需走到中间即可。
为了获得您正在寻找的效果,您可以在计算字符串是否为回文之前对空格、标点符号和字符串大小写进行规范化。
代码
from string import punctuation
def is_palindrome(s):
return all(s[i] == s[-(i + 1)] for i in range(len(s)//2))
def normalized_palindrome(s):
return is_palindrome("".join(c for c in s.replace(" ","").lower() if c not in punctuation))
您还可以使用zip
andreversed
对字母进行成对迭代:
def is_palindrome(s):
return all(a == b for a, b in zip(s, reversed(s)))
当然,这并不止于中间。
测试
>>> tests = [
... "able was I ere I saw Elba",
... "a man, a plan, a canal: Panama!",
... "Was it Eliot's toilet I saw?",
... ]
>>>
>>> for test in tests:
... print normalized_palindrome(test)
...
True
True
True
你的代码
至于您的原件,我是正确的:
>>> s = "able was I ere I saw Elba".lower()
>>> def ispalindrome(word):
... if len(word) < 2: return True
... if word[0] != word[-1]: return False
... return ispalindrome(word[1:-1])
...
>>> ispalindrome(s)
True
>>> s = "a man a plan a canal panama"
>>> ispalindrome(s)
False
>>> ispalindrome(s.replace(" ",""))
True