Check parity / oddness for Palindrome?

Is it okay to check the odd / even length of the palindrome number / line? Most of the snippets I came across do not do this basic test. If the 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 better (for example, faster) to start a direct comparison of the first and last numbers / letters?

Edit : Well, stupid question, had to think twice! :)

+4
source share
7 answers

ABBA is an example of a four-letter palindrome , meaning even length.

A palindrome is a word, phrase, number, or other sequence of characters that are read the same backward or forward ...

+22
source

The easiest way to check the palindrome is to simply compare the string with the opposite:

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

This uses negatively spaced extended slices to go back through s and get the opposite.

+10
source

baab = palindrome and has a length of 4, which even

+8
source

Try the following:

 is_palindrome = lambda s : all(s1==s2 for s1,s2 in zip(s[:len(s)/2],s[-1:-(len(s)+1)/2:-1])) 

checks the front half with the back half and closes as soon as a mismatch is detected.

+3
source

Simple case: aa.

More complicated case: aaaa.

And so on.

+2
source

Even string lengths can also be palindromes. Wikipedia says nothing about this limitation.

+1
source
 n=raw_input("Enter a string==>") n=int(n) start=0 term=n while n>0: result=n%10 start=start*10+result n=n/10 print start if term==start: print "True" else: print "False" 
0
source

All Articles