0

文字列を取り、その文字列が回文であるかどうかを返す関数を派生させる必要があり、私の関数は、スペースが考慮されていない場合、回文である文字列に対して True を返す必要があります (したがって、「男は運河を計画する」と言う必要があります)。パナマ」または「私が見たエリオットのトイレだった」は回文です)、大文字化や句読点のバリエーションを考慮する必要はありません (したがって、「男、計画、運河 - パナマ!」および「それはエリオットのものでしたか?」に対して 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を使用しています

4

3 に答える 3

5
>>> text = 'a man a plan a canal panama'
>>> x = ''.join(text.split())
>>> x == x[::-1]
True
于 2013-03-24T00:49:52.677 に答える
1

概要

i 番目の文字が len-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))

zipand を使用し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
于 2013-03-24T02:28:00.980 に答える