hobson42 at gmaiil.com
Fri Aug 27 18:37:36 CEST 2010
On 27/08/2010 09:53, 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 == pal[-1]:
> return True
> print i_palindrome('annab')
If you want to or must do it recursively.
(Shown in pseudo code to make the logic clearer)
''' test pal (a list) is a palindrome '''
if length of pal = 1
return True # all one letter strings are palindromes.
if first equals last
# pal could be a palindrome
# so test inner part
p = pal with first and last removed
return isPalendrome(p) # and true - implied
return False # it can't be
Of course, the simpler way is to use the definition of a Palindrome as
the same backwards and forwards.
return pal == pal.reverse
More information about the Python-list