palindrome iteration

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Aug 27 11:52:08 CEST 2010

Baba a écrit :
> level: beginner
> the following code looks ok to me but it doesn't work.

"doesn't work" is about the most useless description of a problem. 
Please specify what you expected and what actually happens.

> I would like
> some hints as to where my reasoning / thought goes wrong
> def i_palindrome(pal):
>  while len(pal)>1:
>   if pal[0] == pal[-1]:
>    pal=pal[1:-1]

Can you explain what happens if pal[0] != pal[-1] ? (answer below)

>  return True

> print i_palindrome('annab')

And then you go in an infinite loop !-)

> my reasoning:
> - i check the length of the string: if > 1 continue
> - i check first and last char: if they are equal continue
> - create a new, shorter string starting at index 1 and ending at
> second last index (up to but not including index-1
> -restart the while loop as long as length of string is > 1
> - exiting this loop means all compared chars were identical hence it
> is a palindrome and i return True

Your problem is that when first and last char are not equal, you don't 
exit the while loop. You need a "return False" somewhere here, ie:

def is_palindrom(pal):
   while len(pal)>1:
     # NB : inverted the test here to make exit more obvious
     if pal[0] != pal[-1]:
       return False
   return True

Now there is another solution. A palindrom is made of two symetric 
halves, with (odd len) or without (even len) a single char between the 
symetric halves, ie :

* odd : ABCBA ('AB' + 'C' + 'BA')
* even : ABCCBA ('ABC' + 'CBA')

So you just have to extract the symetric halves, reverse one, and 
compare both (case insensitive compare while we're at it). Here's a 
possible (and a bit tricky) Python 2.x implementation:

def is_palindrom(s):
     s = s.lower()
     slen = len(s)
     until = slen / 2 # Python 2x integer division
     offset = int(not(slen % 2))
     runtil = until - offset
     return s[0:until] == s[-1:runtil:-1]

More information about the Python-list mailing list