Is it a good idea to check for odd/even length of a palindrome number/string? Most snippets I came across don't do this basic test. If length is even, it can't be a palindrome, no?
if len(var) % 2 != 0:
# could be a palindrome, continue...
else:
break
Or is it just better (i.e faster) to start comparing the first and last numbers/letters directly?
Edit: Okay, stupid question, should've thought twice! :)
ABBA - an example of palindrome of four letters meaning even length.
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward...
The easiest way to check for a palindrome is to simply compare the string against it's reverse:
def ispalindrome(s):
return s == s[::-1]
This uses extended slices with a negative step to walk backwards through s
and get the reverse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With