需要推导回文函数
我需要写一个函数,这个函数接收一个字符串,然后判断这个字符串是否是回文。回文的意思是从前往后读和从后往前读是一样的。我的函数应该在不考虑空格的情况下,返回True给那些是回文的字符串,比如“a man a plan a canal panama”或者“was it eliots toilet i saw”。不过,它不需要考虑字母的大小写和标点符号的不同,所以像“A man, a plan, a canal - Panama!”和“Was it Eliot’s toilet I saw?”这些就可以返回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。
3 个回答
你可以先把没有特殊字符和空格的字符串存起来,然后再检查它是不是一个回文。
def isPalindrome(s: str) -> bool:
mystring = s.lower()
mystring2 = ""
for i in mystring:
if i.isalnum():
mystring2 += i
return (mystring2 == mystring2[::-1])
大纲
一个短语如果是回文,那就是它的第i个字符和倒数第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
和 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
在编程中,有时候我们会遇到一些问题,尤其是在使用特定的工具或库时。比如,有人可能在使用某个库时,发现它的某个功能没有按预期工作。这种情况下,通常需要检查代码,看看是不是哪里出错了。
有时候,问题可能出在我们对这个库的理解上,或者是我们没有正确使用它的功能。为了找到解决办法,很多人会去网上查找相关的讨论,比如在StackOverflow上提问或搜索别人遇到的类似问题。
在这些讨论中,大家会分享自己的经验,提供解决方案,或者解释为什么会出现这样的情况。这些信息对于编程新手来说非常有帮助,因为它们可以帮助你更好地理解工具的使用方法,避免犯同样的错误。
总之,遇到问题时,不要着急,先检查自己的代码,看看有没有疏漏,然后可以去网上寻找答案,学习别人的经验。
>>> text = 'a man a plan a canal panama'
>>> x = ''.join(text.split())
>>> x == x[::-1]
True