March 4, 2017
Python anagram solver
Anagram solver in python
Two strings are anagrams if they contain the same set of characters regardless of the order of individual characters such as “earth” and “heart”. Write python code to detect if two strings are anagrams.
Python anagram solver code
Here is the code in python. You may also check this solution in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# Input strings str1 = "heart" str2 = "earth" # Sort each string then do comparison # If the sorted strings are identical # then they are anagram strings if ''.join(sorted(str1)) == ''.join(sorted(str2)): print "Using sorting : Yes they are anagrams" else: print "Using sorting : No they are not anagrams" # Another way is to use a dictionary # Use the character as the key and its count # as the value. If each character in one string # is found in the other string with the same # count then they are anagrams. Using a dictionary # or hash table not only solves the problem but # also gives us fast lookup in linear time # Initialize dictionaries dic1 = {} dic2 = {} for char in str1: dic1[char] = 0 for char in str2: dic2[char] = 0 # Add characters and their counts to the dictionary for char in str1: dic1[char]+= 1 for char in str2: dic2[char]+= 1 anagrams = True for char in str1: # Current character must exist # in both strings with the same count if char in dic2: if dic1[char] != dic2[char]: print "Using dictionary : No they are not anagrams" anagrams = False break # If the character in the first string is not # found in the second string then they are not # anagram strings else: print "Using dictionary : No they are not anagrams" anagrams = False break if anagrams: print "Using dictionary : Yes they are anagrams" |
Thanks for visiting. Please use the comments section below for feedback.