Palindrome

Written by Eric Roberts, adapted by Chris Piech


This program determines if a given string is a palindrome. A string is a palindrome if it is the same forward as backwards, disregarding punctuation, capitalization and whitespace. For example:

  • Abba
  • Racecar
  • Kayak
  • Mr. Owl ate my metal worm.
  • Go hang a salami! I'm a lasagna hog.
  • Elu par cette crapule

Strategy

Our strategy is simple, we are going to perform two steps. First we are going to normalize the given string: remove whitespace and non-alpha characters and making the string lowercase. Then we are going to test if the normalized string is == to the reverse of the normalized string. Simple. Elegant. Effective.


Solution

# some examples
SIMPLE = 'kayak'
KOREAN = '여보, 안경 안보여'
OWL = 'Mr. Owl ate my metal worm.'
HINDI = 'कडक'

def main():
    original = HINDI
    print(original)

    if is_palindrome(original):
        print('Is a palindrome of length ' + str(len(original)) + ' characters')
    else:
        print('Is not a palindrome...')

def is_palindrome(str):
    '''
    >>> is_palindrome('racecar')
    True
    >>> is_palindrome('chris')
    False
    '''
    normalized = normalize(str)
    rev = reversed(normalized)
    return normalized == rev

def normalize(str):
    '''
    >>> normalize('abc ! def')
    'abcdef'
    >>> normalize('여보, 안경')
    '여보안경'
    '''
    normalized = ''
    for ch in str:
        if ch.isalpha():
            normalized += ch.lower()
    return normalized

def reversed(str):
    '''
    Takes a string and returns a reversed copy
    >>> reversed('stressed')
    'desserts'
    >>> reversed('hello')
    'olleh'
    '''
    return str[::-1]

if __name__ == '__main__':
    main()