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)