我需要派生一个函数,该函数接受一个字符串并返回该字符串是否为回文,如果不考虑空格,我的函数应该在为回文的字符串上返回True(所以它应该说‘一个人计划一条运河巴拿马’或‘我看到的是eliots厕所吗’是回文(,但它不需要考虑大写或标点符号的变化(所以它可能会在"一个人,一个计划,一条运河——巴拿马!"one_answers"我看到的是艾略特的厕所吗?"上返回False(。
我试过
def palindrome(s):
return len(s) < 2 or s[0] == s[-1] and palindrome(s[1:-1])
和
def ispalindrome(word):
if len(word) < 2: return True
if word[0] != word[-1]: return False
return ispalindrome(word[1:-1])
但两者都不起作用。有什么建议吗?我使用的是python 3.3
>>> text = 'a man a plan a canal panama'
>>> x = ''.join(text.split())
>>> x == x[::-1]
True
大纲
如果第i个字符与第len个字符相同,则短语为回文。由于这个系列是一个镜像,所以你只需要走到中间。
为了获得您想要的效果,您可以在计算字符串是否为回文之前对空白、标点符号和字符串大小写进行规范化。。
代码
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
和reversed
在字母上成对迭代:
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
您可以存储没有特殊字符和空格的字符串,然后检查它是否是回文。
def isPalindrome(s: str) -> bool:
mystring = s.lower()
mystring2 = ""
for i in mystring:
if i.isalnum():
mystring2 += i
return (mystring2 == mystring2[::-1])