4

我有一个期末考试,老师说他计划在问题列表中加入一个回文检查器。基本上,我需要编写两个单独的函数,一个用于测试列表是否为回文(如果是,则返回 True),另一个用于测试字符串。

这是我到目前为止所拥有的。这似乎给我带来了麻烦:

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

This is your function, the naive way. Works both with odd and even palindromes, lists and strings:

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

The other question is, are palindromes only odd or even sequences, or both? I mean should both abccba and abcba match, or just one of them?

You can add a test if you want only odd or even sequences to be considered as a palindromes:

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]

Only one function, as string are lists of characters. You still can make an alias if your teacher really wants two functions:

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