Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Tuesday, May 7, 2013

Palindrome Word


Problem: Check whether a word is palindrome or not. Make sure it is not case-sensitive, i.e. AbCBa should be a palindrome.

Solution in Python:


import math

UPPER_TO_LOWER_OFFSET = ord('a') - ord('A')

def check_for_palindrome(word):
    """
    Author: Mayur P Srivastava
    """

    n = len(word)

    for i in range(int(math.floor(n // 2))):
        if not canonical_equals(word[i], word[n - i - 1]):
            return False

    return True


def canonical_equals(letter1, letter2):
    ascii1 = canonical_ascii(ord(letter1))
    ascii2 = canonical_ascii(ord(letter2))
    return ascii1 == ascii2


def canonical_ascii(ascii):
    if ascii >= 65 and ascii <= 90:
        return ascii + UPPER_TO_LOWER_OFFSET
    return ascii

Concepts Learned: Single loop.




No comments:

Post a Comment