2013-03-24 1 views
0

문자열을 취하여 그 문자열이 회귀 식인지 여부를 반환하는 함수가 필요합니다. 공백이 고려되지 않은 경우 회문 문자열에 True를 반환해야합니다 '남자는 계획 운하 파나마'또는 '내가 본 eliots 화장실이었다'는 말을해야하지만, 그것은 대문자 또는 문장 부호의 변형을 고려할 필요가 없습니다 (그래서 그것은 '남자, 계획, 운하 - 파나마! '그리고'내가 본 Eliot의 화장실 이었니? ').회문 함수에 대한 함수를 파생해야합니다

나는

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

을 시도했지만 모두 작동하지 않았다. 어떤 제안? 나는 문자 i 번째가 LEN-i 번째 문자와 동일한 경우 문구가 회문입니다 파이썬 3.3

답변

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

이에서 기능을 구현하기 위해? – Kuma

1

개요

을 사용하고 있습니다. 시리즈가 거울 이미지이기 때문에 중간까지만 가야합니다.

당신이 찾고있는 효과를 얻으려면, 당신은 문자열이 회문인지 여부를 계산하기 전에 공백, 문장 부호 및 문자열 경우에 정상화 할 수 있습니다 ..

코드

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