4

I have a final coming up, and the teacher has said that he plans to include a palindrome checker on the list of problems. Basically, I need to write two separate functions, one to test if a list is a palindrome (if it is, return True), and the other to test a string.

Here is what I have so far. It seems to be giving me trouble:

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

I'm not really sure where to go from there.

cedbeu
  • 1,919
  • 14
  • 24

2 Answers2

9

For a list or a string:

seq == seq[::-1]
jamylak
  • 128,818
  • 30
  • 231
  • 230
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)
cedbeu
  • 1,919
  • 14
  • 24