need to derive a function for palindrome

醉酒当歌 提交于 2020-01-16 13:58:42

问题


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?’).

I have tried

def palindrome(s):
    return len(s) < 2 or s[0] == s[-1] and palindrome(s[1:-1])

and

def ispalindrome(word):
    if len(word) < 2: return True
    if word[0] != word[-1]: return False
    return ispalindrome(word[1:-1])

but both didn't work. Any suggestions? I'm using python 3.3


回答1:


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



回答2:


Outline

A phrase is a palindrome if the i'th character is the same as the len-i'th character. Since the series is a mirror image, you haveto go only as far as the middle.

To get the effect you are looking for,you can normalize on whitespace, punctuation, and string case before calculating whether a string is a palindrome or not..

Code

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

You can also use zip and reversed to iterate pairwise over letters:

def is_palindrome(s):
    return all(a == b for a, b in zip(s, reversed(s)))

Of course, that does not stop in the middle.

Test

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

Your code

As for your original, it's correct by me:

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


来源:https://stackoverflow.com/questions/15593869/need-to-derive-a-function-for-palindrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!