View Single Post
Old 02-24-2011, 09:43 AM   #10
cowsonparade
Junior Member

Activity Longevity
0/20 11/20
Today Posts
0/11 ssssssss9
Lightbulb

Well, depends on the definition of optimization:

Code:
def isPalindrome(string):
    #More of a C-style optimization for memory usage
    for i in range(len(string)/2): #rounds down, which is OK because middle letter can be ignored
        if string[i] != string[-i-1]:
            return False
    else: return True

def isPalindrome(string):
    #Optimizes developer time XD
    return string == reverse(string)
I'm a big fan of http://projecteuler.net/ for programming puzzles. A friend of mine would try to solve each one with 1 line.


Quote:
Originally Posted by Tonsko View Post
Apologies for thread resurrection.

I saw this last night while browsing, and it's a nice little problem, if not especially taxing. As a novice, I originally thought it would be best to break it down into an array and do something complicated such as reversing the order of the array and then comparing them. But there is no need - after further reading, having seen the string tools available. Once I was thinking along those lines, it took about 20 mins.

So here's a solution (in python rather than C) - anyone got any optimisation tips?

Code:
#!/usr/bin/python

def isPalindrome(string):
    length = len(string)
    #print length
    
    i=0
    j=length
    
    while j > 0:
    	if string[i] == string[j-1]:
    		#print string[i],string[j-1]
    		i=i+1
    		j=j-1
    	else:
		print 'Not a palindrome'
		break
    	
    	if j == 0:
    		print 'Word is a palindrome'
    	else:
    		pass
    		
input = raw_input()
isPalindrome(input)
The mild advantage of this is that it's not typed, so works equally well with palindromic numbers. For the c problem, I guess you'd have to put in some type checking to sanitise the input before doing anything.

Last edited by cowsonparade : 02-24-2011 at 09:43 AM. Reason: Code, not quote
cowsonparade is offline