# Python: palindrome checking function

I created a reasonable palindrome checking function in python.

Method 1

def ispalindrome(num):
n=str(num)
while len(n)>1:
print n
if n[0]!=n[-1]:
return 0
n=n[1:-1]
return 1

I thought that it would be faster avoiding a string conversion, and to somehow use the modulus (modulo) function. However when I came to write it, I found it quite difficult to code, and I’m sure there must be a better way.

Method 2

def ispalindrome2(num):
l=1
while num/10**l>=1.0:
l+=1
r=0
d=[]
for i in range(1,l+1):
p=num%10**i-r
r+=p
p=p/10**(i-1)
d.append(p)

for i in range(0,l/2):
if d[i]!=d[-i-1]:
return 0
return 1

Doing the speed tests show that Method 1 is over 5.2 times faster than Method 2.

Method 1
0.355437994003 Seconds elapsed
Method 2
1.85815691948 Seconds elapsed

Update: Mike of mikemeat sent me his method using slices (Method 3) and I adapted it slight (Method 4), then shortly after I realised it could be even more efficient by not needing to differentiate between even and odd strings (Method 5).

Method 3

def ispalindrome3(x):
z = str(x)
if len(z)%2 == 0 and z[:len(z)/2]==z[-len(z)/2:][::-1]:
return 1
if len(z)%2 != 0 and z[:(len(z)- 1)/2]==z[(-len(z) + 1)/2:][::-1]:
return 1
else:
return 0

Method 4

def ispalindrome4(x):
z = str(x)
if z[:len( z)/2]==z[len( z)/2+len( z)%2:][::-1]:
return 1
return 0

Method 5

def ispalindrome5(x):
z = str(x)
l=len(z)/2
if z[:l]==z[-l:][::-1]:
return 1
return 0
Method 1
0.357168912888 Seconds elapsed
Method 2
1.83943104744 Seconds elapsed
Method 3
0.179126977921 Seconds elapsed
Method 4
0.179482936859 Seconds elapsed
Method 5
0.149376153946 Seconds elapsed

1. Mike

Very good mat!

2. l0nwlf

def ispalindrome(x):
if str(x) == str(x)[::-1]: return 1
return 0

3. mat

Ah of course, that’s much more elegant!
I’ll do some speed tests later and add them to the post.

I do enjoy getting my ass handed to me if I get to learn something in the process ;P

4. Wolfgang

By my tests, the above commenter’s post takes 5.525s for 10000016 iterations. By contrast, your fastest method (method 5) takes 12.345s, or about twice as long.

5. prinkesh

method 5 is needs a bit of tweak :
it gives wrong ans test it for num = 989

6. divyanand

def ispalindrome5(x):
z = str(x)
print z[0:]==z[::-1]

this gives true/false in less time. check it out

7. DiZ

To complete previous post: return boolean directly

def is_palindrom(word):
return word == word[::-1]