#!/usr/bin/env python # # Author : Ahmed Obied (amaobied@ucalgary.ca) # Date : Jan. 17th 2008 # Purpose : Checks if two strings are palindromes and checks if the # two strings are anagrams of each other. # # constant for the total number of letters from 0 - 25 (26 in total) TOTAL_LETTERS = 25 def is_palindrome(str): """ Purpose : checks if a string is a palindrome Parameters : str - the string to check Returns : true if the string is a palindrome, false otherwise """ # convert all characters in the string to upper case str = str.upper() # used to go from the start of the string to the end f_ptr = 0 # used to go from the end of the string to the start s_ptr = len(str) - 1 # stop iterating when we hit first pointer reaches the end of the string while f_ptr < len(str): # if the two characters are not equal then it's can't be a palindrome if str[f_ptr] != str[s_ptr]: return False else: # increment the first pointer and decrement the second pointer f_ptr = f_ptr + 1 s_ptr = s_ptr - 1 return True def is_anagram(fst_str, sec_str): """ Purpose : checks if two strings are anagrams of each other Parameters : fst_str, sec_str - the strings to check Returns : true if the two strings are anagrams of each other, false otherwise """ ret_value = False # if the two strings have different length then they can't be anagrams of each other if len(fst_str) == len(sec_str): # initalize each location in both lists to zero fst_chars = [0 for i in range(TOTAL_LETTERS)] sec_chars = [0 for i in range(TOTAL_LETTERS)] # count the appearance of each characters in the strings for i in range(len(fst_str)): # get the decimal representation of a letter module the total number of letters fst_tmp = ord(fst_str[i].upper()) % TOTAL_LETTERS sec_tmp = ord(sec_str[i].upper()) % TOTAL_LETTERS # use the decimal representation as an index into the char lists and increment the # occurence of a given character fst_chars[fst_tmp] = fst_chars[fst_tmp] + 1 sec_chars[sec_tmp] = sec_chars[sec_tmp] + 1 ret_value = True # if each index in the lists match then the strings are anagrams for i in range(25): if fst_chars[i] != sec_chars[i]: ret_value = False break return ret_value if __name__ == '__main__': """ Main Entry """ fst_str = raw_input('Enter the first string: ') sec_str = raw_input('Enter the second string: ') # check the string to see if the two strings are palindrome if is_palindrome(fst_str): print 'The string %s is a palindrome' % fst_str else: print 'The string %s is not a palindrome' % fst_str if is_palindrome(sec_str): print 'The string %s is a palindrome' % sec_str else: print 'The string %s is not a palindrome' % sec_str # check the two strings to see if they are anagrams of each other if is_anagram(fst_str, sec_str): print 'The strings %s and %s are anagrams of each other' % (fst_str, sec_str) else: print 'The strings %s and %s are not anagrams of each other' % (fst_str, sec_str)