Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check even/odd for Palindrome?

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! :)

like image 995
eozzy Avatar asked Jan 19 '10 17:01

eozzy


2 Answers

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...

like image 158
TabbyCool Avatar answered Sep 26 '22 10:09

TabbyCool


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.

like image 40
sth Avatar answered Sep 23 '22 10:09

sth