Friday, October 15, 2010

Python - palindrome detector

# palindrome detector
#
# parse text and print out palindromes
 
 
# make a map to remove punctuation
punc = {" ":'', ",":'',
        ".":'', "!":'',
        "?":'', "'":'',
        '"':'', ':':'',
        '\n':''}
puncMap = str.maketrans(punc)
 
# determines whether given text is a palindrome
def isPalindrome(text):
    # change to all the same case
    text = text.lower()
    # remove punctuation
    text = text.translate(puncMap)
    # to count as a palindrome it must have
    # at least 2 valid characters
    if (len(text) < 2):
        return False
    # palindrome if it reads the same
    # front or backwards
    return text == text[::-1]
 
 
givenText = """
    Hi Mom, welcome. A man, a plan, a canal, panama. And 
    other text. 
    """
 
# first check the whole text
if (isPalindrome(givenText)):
    print("The entire text: '" + givenText.strip() + "' is a palindrome.")
 
# now check by sentence
for sentence in givenText.split('.'):
    if (isPalindrome(sentence)):
        print("The sentence: '" + sentence.strip() + "' is a palindrome.")
 
# now check every word
for word in givenText.split(' '):
    if (isPalindrome(word)):
        print("The word: '" + word.strip() + "' is a palindrome.")
 
# my output:
# The sentence: 'A man, a plan, a canal, panama' is a palindrome.
# The word: 'Mom,' is a palindrome.
 
    
 
 

No comments:

Post a Comment