Anagram Program In Python
Here we will write a program to check whether two given strings are anagrams. Here is the algorithm for an anagram program in Python.
Pseudocode
String s1, s2
# Frequncy array
Array a1[26], a2[26]
# Strings taken as input
input -> s1
input -> s2
# Convert to lowercase
s_1 = s1.lower()
s_2 = s2.lower()
for letter in s_1:
if letter is alphabet:
# Update frequency of lettter in array
a1[letter-’a’]+=1
for letter in s_2:
if letter is alphabet:
a2[letter-’a’]+=1
is_anagram = 1
for i in range(26):
if a1[i]!=a2[i]:
# frequency of occurrence of letters is different thus it is not an anagram
is_anagram = 0
break
if is_anagram == 1:
print(“The strings are anagrams of each other”)
else:
print(“The Strings are not anagrams”)
Now let us implement this algorithm for an anagram program in Python.
We can implement the anagram program in Python in a few different ways. Here let us implement the frequency approach first.
Methods to Check If Two Strings Are Anagrams
- Using Frequency Counter
- Using Sorting
- Using Inbuilt List and Sort() Methods
- Using a dictionary to achieve constant time complexity
- Using list and dictionary
Method 1:- Anagram Program in Python Using Frequency Counter
In this approach, we will try to calculate the frequency of occurrence of each alphabet in both strings. If each letter occurs with the same frequency in both strings, then the strings are anagrams of each other.
Python
# Anagram Program in Python
from collections import Counter
s1 = input("Enter the first string: ")
s2 = input("Enter the second string: ")
# Handling cases with inconsistent capitalization
s_1 = s1.lower()
s_2 = s2.lower()
'''
The Counter function in Python collections gives a frequency dictionary for the strings
where the frequency of each character is calculated.
'''
is_anagram = Counter(s_1) == Counter(s_2)
if is_anagram == 1:
print("The strings "+s1+" and "+s2+" are anagrams!")
else:
print("The strings "+s1+" and "+s2+" are not anagrams!")
You can also try this code with Online Python Compiler
Run Code
Output:
Enter the first string: abode
Enter the second string: adobe
The strings abode and adobe are anagrams!
Another approach for the anagram program in Python is to sort the strings to be checked. If the strings are equal after sorting, then the strings are anagrams of each other.
Also see, Swapcase in Python
Method 2:- Anagram Program in Python Using Sorting
In this approach, we will first convert all the letters in the strings to lowercase. After doing that, we will sort the strings and compare them. If both are equal, the strings are anagrams of each other.
Python
# Anagram Program in Python
s1 = input("Enter the first string: ")
s2 = input("Enter the second string: ")
# Handling cases with inconsistent capitalization
s_1 = s1.lower()
s_2 = s2.lower()
# The sorted function returns the sorted string
is_anagram = sorted(s_1) == sorted(s_2)
if is_anagram == 1:
print("The strings "+s1+" and "+s2+" are anagrams!")
else:
print("The strings "+s1+" and "+s2+" are not anagrams!")
You can also try this code with Online Python Compiler
Run Code
Output:
Enter the first string: race
Enter the second string: care
The strings race and care are anagrams!
You can practice by yourself with the help of online python compiler.
Method 3:- Anagram Program in Python using Inbuilt List and Sort() Methods
In this approach, we first convert the given words into a list of characters in Python. While converting it to a list, we make all the characters to handle the inconsistencies with capitalization. Now, we sort the lists and compare them. If the list are equal, the strings are anagram else not.
Python
def anagram(word1, word2):
# Handling cases with inconsistent capitalization
list1 = list(word1.lower())
list2 = list(word2.lower())
# Sort the character lists
list1.sort()
list2.sort()
# Check if the sorted lists are equal
if list1 == list2:
return True
else:
return False
# Example usage
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")
if anagram(word1, word2):
print(f"The Strings {word1} and {word2} are anagrams!")
else:
print(f"The Strings {word1} and {word2} are not anagrams!")
You can also try this code with Online Python Compiler
Run Code
Output:
Enter the first word: listen
Enter the second word: silent
The Strings listen and silent are anagrams!
Method 4:- Anagram Program in Python using a dictionary to achieve constant time complexity
In this approach, we make a mapping of characters present in a string with their corresponding frequencies. We make two Python dictionaries, each for the given words. Now, we populate these dictionaries and compare the final populated frequency dictionaries. If the dictionaries are equal, the strings are anagrams; else not.
The above-explained approach helps us to perform the operation in constant time complexity.
Python
def anagram(word1, word2):
# Handling cases with inconsistent capitalization
word1= word1.lower()
word2= word2.lower()
# We make dictionaries to store frequencies
freq1 = {}
freq2 = {}
# store frequencies of character of word1
for char in word1:
freq1[char] = freq1.get(char, 0) + 1
# store frequencies of character of word1
for char in word2:
freq2[char] = freq2.get(char, 0) + 1
# Check if the dictionaries are equal
if freq1 == freq2:
return True
else:
return False
# Example usage
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")
if anagram(word1, word2):
print(f"The Strings {word1} and {word2} are anagrams!")
else:
print(f"The Strings {word1} and {word2} are not anagrams!")
You can also try this code with Online Python Compiler
Run Code
Output:
Enter the first word: earth
Enter the second word: heart
The Strings listen and silent are anagrams!
Method 5:- Anagram Program in Python using list and dictionary
In this approach, we try to optimize the program by using a list and a dictionary in the code. Here, firstly we first convert the given words into a list of characters in Python. While converting it to a list, we make all the characters handle the inconsistencies with capitalization. Now we check for the length of the lists; if they are not equal, we return false.
Now, if the length of the lists is equal, we make two Python dictionaries, each for the given words. Now, we populate these dictionaries and compare the final populated frequency dictionaries. If the dictionaries are equal, the strings are anagrams; else not.
Python
def anagram(word1, word2):
# Handling cases with inconsistent capitalization
word1_list = list(word1.lower())
word2_list = list(word2.lower())
# Checking if the length of list are equal
if len(word1_list) != len(word2_list):
return False
# Creating dictionaries
freq1 = {}
freq2 = {}
# store frequencies of character of word1
for char in word1_list:
freq1[char] = freq1.get(char, 0) + 1
# store frequencies of character of word2
for char in word2_list:
freq2[char] = freq2.get(char, 0) + 1
# Check if the dictionaries are equal
if freq1 == freq2:
return True
else:
return False
# Example usage
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")
if anagram(word1, word2):
print(f"The Strings {word1} and {word2} are anagrams!")
else:
print(f"The Strings {word1} and {word2} are not anagrams!")
You can also try this code with Online Python Compiler
Run Code
Output
Enter the first word: integral
Enter the second word: triangle
The Strings listen and silent are anagrams!
Also read palindrome number in python.
Frequently Asked Questions
Q. What is an Anagram?
Two words are said to anagrams of each other if they contain the same letters, just in a different order. Example: LISTEN and SILENT.
Q. What is anagram in python with example?
An anagram in Python refers to rearranging the letters of one word or phrase to form another word or phrase. For example, "listen" and "silent" are anagrams because they use the same letters.
Q. What is the anagram game in python?
The anagram game in Python involves generating anagrams of a given word or phrase and asking the player to guess the original word or phrase.
Q. How do you find anagrams in a list of words in python?
To find anagrams in a list of words in Python, you can iterate through the list, sorting each word's letters alphabetically and comparing them. Words with the same sorted letters are anagrams.
Q. How do you find anagrams?
To find anagrams, you can compare the sorted versions of two words. If they match, the words are anagrams. For example, "listen" and "silent" are anagrams because when sorted alphabetically, they both become "eilnst."
Conclusion
In this article, we discussed a Python program to check if two strings are anagram. Learning how to check for anagrams in Python is a useful skill for word games and data analysis. With the easy program we've covered, you can now quickly tell if two words are anagrams.
Recommended Reading:
Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available.
Also check out - Data Dictionary In Software Engineering.
Have a look at the interview experiences and interview bundle for placement preparations. Nevertheless, consider our paid courses to give your career an edge over others!
Cheers!