Check Anagrams in Python

by igor.ganapolsky

This post is about verifying whether two strings are anagrams of each other.  For example: “bad credit” and “debit card” are anagrams.  This problem has been presented many times over the past years in the comp sci community, and everybody thinks they have the most efficient solution.  I have come up with the simplest solution possible in Python.  Not sure if it is the most ‘efficient’, but it’s sure as heck simple!

def isAnagram(string1, string2):
    string1_val = 0
    string2_val = 0
    for ch1 in string1:
      if (not ch1.isspace()): string1_val += int(ch1.encode('hex'), 16)
    for ch2 in string2:
      if (not ch2.isspace()): string2_val += int(ch2.encode('hex'), 16)
  
    return string1_val == string2_val

if __name__ == "__main__":
    input_string1 = raw_input ("Enter the first word/phrase: ")
    input_string2 = raw_input ("Enter the second word/phrase: ")
    if isAnagram(input_string1, input_string2): print "Is an anagram"
    else: print "Not an anagram"
Advertisements