4

私は最終問題を控えており、先生は問題のリストに回文チェッカーを含める予定だと言っています。基本的に、リストが回文かどうかをテストする関数 (回文である場合は True を返す) と、文字列をテストする関数の 2 つの別個の関数を記述する必要があります。

これが私がこれまでに持っているものです。それは私に問題を与えているようです:

def palindrome(s)
index = 0
index = True
     while index < len(s)        
        if n[index]==n[-1-index]
        index=1
        return True
     return False

そこからどこへ行けばいいのかよくわかりません。

4

2 に答える 2

9

リストまたは文字列の場合:

seq == seq[::-1]
于 2013-05-16T11:51:07.567 に答える
2

これがあなたの機能であり、素朴な方法です。奇数と偶数の回文、リスト、文字列の両方で機能します。

def is_palindrome(s):
    return s == s[::-1]

もう 1 つの問題は、回文は奇数列または偶数列だけなのか、あるいはその両方なのかということです。つまり、両方abccbaabcba一致する必要がありますか、それともどちらかだけですか?

奇数または偶数シーケンスのみを回文と見なしたい場合は、テストを追加できます。

def is_palindrome(s, t='both'):
    # only odd sequences can be palindromes
    if t=='odd':
        if len(s)%2 == 0:
            return False
        else:
            return s == s[::-1]

    # only even sequences can be palindromes
    elif t=='even':
        if len(s)%2:
            return False
        else:
            return s == s[::-1]

    # both even or odd sequences can be palindromes
    else:
        return s == s[::-1]

文字列は文字のリストであるため、関数は 1 つだけです。教師が本当に 2 つの機能を必要としている場合は、エイリアスを作成できます。

def is_list_palindrome(l, t='both'):
    return is_palindrome(l, t)
于 2013-05-16T12:29:46.443 に答える