需要得出回文函数

时间:2013-03-24 00:48:04

标签: python palindrome

我需要派生一个函数,它接受一个字符串并返回该字符串是否为回文并且我的函数应该在字符串上返回True,如果不考虑空格(所以它应该说'a man a'计划一个运河巴拿马'或'是我看到的'厕所厕所',但它不需要考虑大写字母或标点符号的变化(所以它可能会在“一个人,一个计划,一条运河 - 巴拿马!'和'上返回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 个答案:

答案 0 :(得分:5)

>>> text = 'a man a plan a canal panama'
>>> x = ''.join(text.split())
>>> x == x[::-1]
True

答案 1 :(得分:1)

概要

如果第i个字符与len-ith字符相同,则短语是回文结构。由于该系列是一个镜像,你必须只到中间。

要获得您正在寻找的效果,您可以在计算字符串是否为回文之前对空格,标点符号和字符串大小写进行标准化。

代码

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))

您还可以使用zipreversed在字母上成对迭代:

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

答案 2 :(得分:0)

您可以存储没有特殊字符和空格的字符串,然后检查它是否是回文。

const isLastThirtyMins = transactions
  .filter(transaction =>
    (new Date().getTime() - new Date(transaction.date).getTime() < THIRTY_MINUTES) &&
    (parseFloat(transaction.value) >= 15));
相关问题