Well, depends on the definition of optimization:
#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]:
else: return True
#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.
Originally Posted by Tonsko
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?
length = len(string)
while j > 0:
if string[i] == string[j-1]:
print 'Not a palindrome'
if j == 0:
print 'Word is a palindrome'
input = raw_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.