Table of contents
1.
Introduction
2.
What is Anagram?
3.
Anagram Program In Python
3.1.
Pseudocode
4.
Methods to Check If Two Strings Are Anagrams
4.1.
Method 1:- Anagram Program in Python Using Frequency Counter
4.2.
Python
4.3.
Method 2:- Anagram Program in Python Using Sorting
4.4.
Python
4.5.
Method 3:- Anagram Program in Python using Inbuilt List and Sort() Methods
4.6.
Python
4.7.
Method 4:- Anagram Program in Python using a dictionary to achieve constant time complexity
4.8.
Python
4.9.
Method 5:- Anagram Program in Python using list and dictionary
4.10.
Python
5.
Frequently Asked Questions
5.1.
How to find anagrams in a list in Python?
5.2.
How do you identify anagrams?
5.3.
How do you calculate anagrams?
6.
Conclusion
Last Updated: Nov 9, 2024
Easy

Python Program to Check if Two Strings are Anagram

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. For instance, the words "listen" and "silent" are anagrams of each other. Checking if two strings are anagrams is a common problem that is often encountered in coding interviews and algorithm challenges. In this blog, we will explore how to write a Python program to check if two given strings are anagrams of each other.

Anagram Program in Python

What is Anagram?

An anagram is a word that is made by rearranging the letters of another word. That is, two strings are anagrams of each other if one can be obtained from the other by simply rearranging. It's like solving a puzzle with letters to create a new word. 

For example, consider the word “TRIANGLE” and the word “INTEGRAL”, both these words are made up of the same letters that occur in the same frequency. Both the strings can be considered as a simple rearrangement of letters ("T", “R”, “I”, “A”, “N”, “G”, “L”, “E”). Therefore both words “TRIANGLE” and “INTEGRAL” are said to be Anagrams.

Anagrams are a fun way to play with words are helps to improve problem-solving skills. They are often used as puzzles and word games as a means of entertainment. It can also be considered a creative way of finding alternative words and expressions given a set of letters.

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

  1. Using Frequency Counter
     
  2.  Using Sorting
     
  3.  Using Inbuilt List and Sort() Methods
     
  4.  Using a dictionary to achieve constant time complexity
     
  5.  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

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

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

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

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

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

How to find anagrams in a list in Python?

You can find anagrams in a list by sorting each string and comparing them, or by using a frequency count of characters.

How do you identify anagrams?

Anagrams can be identified by checking if two strings have the same characters in the same frequency, irrespective of the order.

How do you calculate anagrams?

To calculate anagrams, compare the sorted versions of the strings or count the frequency of each character and ensure they match.

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 Code360 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!

Live masterclass