Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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.
Q. What is an Anagram?
5.2.
Q. What is anagram in python with example?
5.3.
Q. What is the anagram game in python?
5.4.
Q. How do you find anagrams in a list of words in python?
5.5.
Q. How do you find anagrams?
6.
Conclusion
Last Updated: Mar 28, 2024
Easy

Python Program to Check if Two Strings are Anagram

Introduction

Hey there! Today, we're going to talk about something super cool: anagrams. Ever heard of them? It's when two words have the same letters but in a different order, like "listen" and "silent". Neat, right?

Anagram Program in Python

One such problem that everyone must have come across is the anagram problem. In this article, we will discuss the anagram problem in detail, along with an anagram program in Python to check if the two given strings are anagrams.

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

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!

Live masterclass