Archives for 7 Sep,2009

You are browsing the site archives by date.

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

Read More