palindrome iteration

Jussi Piitulainen jpiitula at ling.helsinki.fi
Fri Aug 27 20:05:55 CEST 2010


Ian writes:

> If you want to or must  do it recursively.
> (Shown in pseudo code to make the logic clearer)
> 
> def isPalindrome(pal)
>      ''' 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
>      else
>          return False # it can't be

def palindromep(s): 
    return ( s == "" or
             ( s[0] == s[-1] and
               palindromep(s[1:-1]) ) )

> Of course, the simpler way is to use the definition of a Palindrome
> as the same backwards and forwards.
> 
> def isPalindrome(pal)
>      return pal == pal.reverse

Agreed. But is there any nicer way to spell .reverse than [::-1] in
Python? There is .swapcase() but no .reverse(), right?



More information about the Python-list mailing list