palindrome iteration

Baba raoulbia at
Fri Aug 27 10:53:17 CEST 2010

level: beginner

the following code looks ok to me but it doesn't work. 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]:
 return True

print i_palindrome('annab')

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


More information about the Python-list mailing list