Palindrome

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Fri Nov 14 00:28:55 CET 2003


On Thu, 13 Nov 2003 23:16:50 GMT, Andrew Dalke wrote:
> Gerrit Holl
>> Are you looking for:
>> 20:58:42:232:0  >>> def ispalindrome(s):
>> 20:58:42:232:0  ...  return s == s[::-1]
>
> No.  The OP wanted to strip special characters and normalize case, so
> that  A man, a plan, a canal -- Panama!  would be allowed as a
> palindrome.

Here's mine.

I have yet to try this on the world's longest palindrome:

    <http://www.norvig.com/palindrome.html>

=====
#!/usr/bin/env python

""" Module for palindrome determination
"""

import string

def is_palindrome( str ):
    """ Determine if str is a palindrome
    """

    # Assume false until proven otherwise
    is_pal = False

    # Remove punctuation and whitespace
    passthrough_tbl = string.maketrans( '', '' )
    remove_chars = string.whitespace + string.punctuation
    str = string.translate( str, passthrough_tbl, remove_chars )

    # Remove capitalisation
    str = string.lower( str )

    # Determine if massaged string matches its reverse
    is_pal = ( str == str[::-1] )

    return is_pal


if( __name__ == '__main__' ):
    candidates = [
        "",
        "Foo",
        "FooF",
        "Foof",
        "Foxof",
        "Madam, I'm Adam.",
        "Ten animals I slam in a net.",
        "Lapses?  Order red roses, pal.",
        "A man, a plan, a canal -- Panama!",
        "Satan, oscillate my metallic sonatas.",
        "Eva, can I stack Rod's sad-ass, dork cats in a cave?",
    ]
    for str in candidates:
        print ( "'%s':" % str ),
        print is_palindrome( str )

=====

-- 
 \     "I wish I had a dollar for every time I spent a dollar, because |
  `\        then, yahoo!, I'd have all my money back."  -- Jack Handey |
_o__)                                                                  |
Ben Finney <http://bignose.squidly.org/>




More information about the Python-list mailing list