需要推导回文功能 [英] need to derive a function for palindrome
问题描述
我需要派生一个接受字符串的函数,并返回该字符串是否是回文,并且如果不考虑空格,则我的函数应该对属于回文的字符串返回True(因此应该说一个男人计划巴拿马运河"或我见过的洗手间厕所是回文式),但不必考虑大小写或标点符号的差异(因此它可能在一个人,一个计划,一条运河-巴拿马!"和我看到的是艾略特的厕所吗?").
I need to derive a function which takes a string and returns whether or not that string is a palindrome and my function should return True on strings which are palindromes if spaces aren’t considered (so it should say that ’a man a plan a canal panama’ or ’was it eliots toilet i saw’ are palindromes), but it need not consider variations in capitalization or punctuation (so it may return False on ’A man, a plan, a canal - Panama!’ and ’Was it Eliot’s toilet I saw?’).
我尝试过
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
but both didn't work. Any suggestions? I'm using python 3.3
推荐答案
>>> text = 'a man a plan a canal panama'
>>> x = ''.join(text.split())
>>> x == x[::-1]
True
这篇关于需要推导回文功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!