An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once such as elbow and below. In this article, we will discuss different methods to check if two strings are anagram or not.
Python strings are amongst the most frequently asked questions for beginners in Python programming. Whether you’re polishing your coding skills or preparing for interviews, there are a few common programs you will definitely come across, for example:
- How to Reverse a String in Python
- How to Convert Python List to String
- How to Check if a Python String is a Palindrome
In this article, we will focus on another such program – how to determine if two strings are anagrams or not using various methods.
Table of Content
- What is an Anagram?
- Methods to Check if Two Strings are Anagrams
But first, for the unaware, let’s talk about what an anagram is, shall we?
What is an Anagram?
An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once. For instance:
All these are examples of anagrams – each word or phrase has the exact same letters as the other, only arranged differently. Interesting, right?
In Python, two strings can be anagrams if all characters of one string can be rearranged into a sequence resulting in another string. Below, we have discussed different ways in which we can check the same:
Methods to Check if Two Strings are Anagrams
Method 1 – Sort both strings and compare
This method first converts both input strings to lowercase and then sorts the strings using the sort() method. The resulting strings are then compared and if they match, they are anagrams. It’s as simple as it sounds!
#Enter input stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: "))#Convert into lowercase and sortstr1 = sorted(str1.lower())str2 = sorted(str2.lower())print("String 1 after sorting: ", str1)print("String 2 after sorting: ", str2)#Define a function to match stringsdef isAnagram():if (str1 == str2) :return "The strings are anagrams."else:return "The strings are not anagrams."print(isAnagram())
Method 2 – Using the counter() method
For this method too, we first convert the strings to lowercase. Then we import the counter from the collections library in Python. We will apply this method to both strings and compare the counters for both strings. If the counters match, the strings are anagrams.
from collections import Counter#Define a function to match countersdef check(str1,str2):print(Counter(str1))print(Counter(str2))if (Counter(str1) == Counter(str2)) :return "The strings are anagrams."else:return "The strings are not anagrams."#Enter input stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: "))#Call the functioncheck(str1.lower(), str2.lower())
Method 3 – Using lists and append() method
Another method is to declare two empty lists l1 and l2. Both input strings are converted to lowercase and appended to l1 and l2 respectively. The lists are then sorted and compared. If matched, the strings are anagrams.
#Enter input stringsstr1 = str(input ("Enter string 1: "))str2 = str(input ("Enter string 2: "))#Declare two empty listsl1=l2=##Convert first string into lowercase#append to list 1#and sortfor i in str1:l1.append(i.lower())l1.sort()##Convert second string into lowercase#append to list 2#and sortfor j in str2:l2.append(j.lower())l2.sort()print("List 1 after sorting: ", l1)print("List 2 after sorting: ", l2)#Define a function to match listsdef isAnagram():if (l2 == l2) :return "The strings are anagrams."else:return "The strings are not anagrams."print(isAnagram())
|Programming Online Courses and Certification||Python Online Courses and Certifications|
|Data Science Online Courses and Certifications||Machine Learning Online Courses and Certifications|
Method 4 – Using count arrays
We are already aware that 1-byte (8-bits) character sets can contain 256 characters. So, in this method, we perform the following steps:
- Create count arrays of size 256 to store the input strings.
- Initialize the count arrays to 0.
- Iterate through all characters of the strings.
- After each iteration, the character count is incremented by one in the corresponding count array.
- Compare the count arrays. If they match, the strings are anagrams.
total_char = 256#Define a function to check if strings are anagramsdef isAnagram(str1, str2):#Create two count arrays and initialize all values as 0count1 =  * total_charcount2 =  * total_char#For each character in input strings,#increment count corresponding to count arrayfor i in str1:count1[ord(i)] += 1for i in str2:count2[ord(i)] += 1#Check if strings are of the same lengthif len(str1) != len(str2):return 0#Compare count arraysfor i in range(total_char):if count1[i] != count2[i]:return 0return 1#Enter input stringsstr1 = str(input ("Enter string 1: ")).lower()str2 = str(input ("Enter string 2: ")).lower()#Function callif isAnagram(str1, str2):print("The strings are anagrams.")else:print("The strings are not anagrams.")
Hope this article will be helpful for you to understand the different ways in which one can check if two Python strings are anagrams or not. If you wish to learn more about Python and practice Python programming, you can explore related articles here.
Top Trending Article
Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python
Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |
Download this article as PDF to read offlineDownload as PDF