palindrome iteration

Dave Angel davea at ieee.org
Fri Aug 27 15:15:25 EDT 2010



Jussi Piitulainen wrote:
> 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?
>
>   
There can't be a .reverse() method on string, because it's immutable.  
You could use

    "".join(reversed(pal))

but I'd prefer  pal[::-1]  as I said earlier.

DaveA




More information about the Python-list mailing list