palindrome iteration
Peter Otten
__peter__ at web.de
Fri Aug 27 05:33:15 EDT 2010
Baba wrote:
> 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]:
> pal=pal[1:-1]
> return True
Do yourself a favour and use 4-space indent. That makes the structure of
your code more obvious.
> 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
If the test pal[0] == pal[-1] fails, i. e. the two compared characters
differ, what happens?
More generally, if pal is not a palindrome, can your function ever return
False? If not, at what point should it?
Peter
More information about the Python-list
mailing list