1

単語が回文であるかどうかを分析するコードを作成しようとしています。ところで、パリンドロームとは、前後に同じように読まれる単語です。例は「マダム」または「正午」

ここに試してみてください:

x = raw_input("please enter a word:\n")
L = len(x)

 # this part returns the first letter of the word

def first(word):
    return word[0]

# this part returns the last letter of the word

def last(word):
    return word[-1]


def middle(word):
    return word[1:-1]


def is_palindrome(word):
    if L <= 2:
        print 'enter a word with at least three letters'
    elif first(word) != last(word):
        print 'This word is not a palindrome'
    else:
        word = middle(word)
        is_palindrome(word)

is_palindrome(x) 

しかし、実行すると、

IndexError: string index out of range
...line 7, in first return word[0]

「is_palindrome」の最初のブランチは完全に機能します。つまり、単語が回文でない場合、エラーは発生しません。同様に「noopn」はエラーなしで実行されますが、エラーは 2 番目のブランチにあります

このコードで何度も遊んできましたが、「反復部分」がわかりません。答えはありますが、まだ見たくありません。私は 2 つのことを理解する必要があります: 1. 関数 is_palindrome の反復を正しく機能させる方法 2. 最後にプログラムを終了する方法。

まだ解決策を提供せずに、これらの質問に答える方法を教えていただけますか?

最後に、printステートメントをどこに置くべきですか: print 'This word is a palindrome'

ありがとうございました

4

6 に答える 6

1

コードに追加の条件を追加すると、問題が解決します。1文字しか残っていない場合は、 is_palindrome() を呼び出す必要はありません

    x = raw_input("please enter a word:\n")
    L = len(x)

     # this part returns the first letter of the word

    def first(word):
        return word[0]


   # this part returns the last letter of the word

    def last(word):
        return word[-1]


    def middle(word):
        return word[1:-1]


    def is_palindrome(word):
        if L <= 2:
            print 'enter a word with at least three letters'
        elif first(word) != last(word):
            print 'This word is not a palindrome'
        else:
            word = middle(word)
            if len(word) > 1:
                is_palindrome(word)
            else:
                print 'This word is a palindrome'

    is_palindrome(x)
于 2013-08-08T04:37:44.460 に答える
0

素晴らしい道順です。すべてが賛成票を獲得しました。

これらの指示により、次の簡潔なコードを作成できました

コード 1

x = raw_input("enter a word to check if it is a palindrome:\n")

if x[::-1] == x:
    print 'yes this one is a palindrome'

else:
    print 'sorry try again by re-running the program'


コード 2

x = raw_input("enter a word to check if it is a palindrome:\n")

if len(x) <= 1:
    print 'Of course ', x, ' is a palindrome'

def is_palindrome(x):    
    if len(x) >= 2:
        if x[0]!=x[-1]:
            print 'This is not a palindrome'
        else:
            x = x[1:-1]
            return is_palindrome(x)
    print 'This is FINALLY a real palindrome'

is_palindrome(x)

関数 is_palindrome を条件ステートメントlen(x) <= 1の 2 番目のブランチとして含めることができると思いますが、コードはすべてこの関数に関するものなので、この方法の方が気に入っています。

于 2013-08-09T02:19:31.647 に答える