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++

# 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"
   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
	# If the character in the first string is not
	# found in the second string then they are not
	# anagram strings
		print "Using dictionary : No they are not anagrams"
		anagrams = False

if anagrams:
   print "Using dictionary : Yes they are anagrams"

Thanks for visiting. Please use the comments section below for feedback.

Leave a Reply

%d bloggers like this: