Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Python Program To Check For Two Strings Is An Anagram

Last Updated on June 6, 2023 by Mayank Dham

An anagram is a word or phrase formed by rearranging the letters of another word or phrase. It is essentially a permutation of the original word or phrase. Anagrams maintain the same set of characters but in a different order.

What is an Anagram?

A word or phrase that has been created by precisely rearranging all the letters of another word or phrase is called an anagram.
Some examples of Anagram are:-

"Listen" and "silent" are anagrams of each other. By rearranging the letters in "listen," we can form the word "silent," and vice versa.

"Dormitory" and "dirty room" are anagrams. The letters in "dormitory" can be rearranged to spell "dirty room," maintaining the same set of characters.

"Eleven plus two" can be rearranged to form the phrase "twelve plus one." Despite having different words, both phrases are anagrams because the letters can be rearranged to create the other phrase.

Anagrams can be found not only in single words but also in longer phrases or sentences. The key characteristic is that the rearrangement of letters must create a new word or phrase while maintaining the same set of characters.

Ways to check if two strings are an Anagram
We have different methods to check if two strings are anagrams or not.

Method 1: Compare after sorting both strings

The two input strings are first made lowercase using this method, which is followed by a sort() operation. When the resultant strings are compared, anagrams are determined if they match.

Implementation

# function to check if two strings are
# anagram or not
def check(s1, s2):
     
    # the sorted strings are checked
    if(sorted(s1)== sorted(s2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")        
         
# driver code 
s1 ="listen"
s2 ="silent"
check(s1, s2)
 

Output

The strings are anagrams.

Method 2 – By counter() method

The strings are first made lowercase. The counter is then imported from Python’s collections package. The counts for the two strings will be compared after applying this procedure to both strings. The strings are anagrams if the counts line up correctly.

Implementation

# Python3 program for the above approach
from collections import Counter

# function to check if two strings are
# anagram or not
def check(s1, s2):

    # implementing counter function
    if(Counter(s1) == Counter(s2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")


# driver code
s1 = "listen"
s2 = "silent"
check(s1, s2)
 

Output

The strings are anagrams.

Method 3 – Using lists and append() method

Declare l1 and l2 to be two empty lists. Both input strings are changed to lowercase and accordingly added to l1 and l2. After that, the lists are compared and sorted. The strings are anagrams if they match.

Implementation

Output

('List 1 after sorting: ', ['e', 'i', 'l', 'n', 's', 't'])
('List 2 after sorting: ', ['e', 'i', 'l', 'n', 's', 't'])
The strings are anagrams.

Conclusion
In conclusion, an anagram of a string is a word or phrase that can be formed by rearranging the letters of the original string. Checking for anagrams involves comparing the characters in both strings and verifying if they have the same frequency as we have discussed various methods in Python and is one of the famous interview questions.

Frequently Asked Questions

Q1. Does the order of characters matter in anagrams?
No, the order of characters does not matter in anagrams. Anagrams are formed by rearranging the letters of a word or phrase, so the characters can appear in any order.

Q2. Do anagrams need to have the same length?
Yes, anagrams must have the same length. Since anagrams involve rearranging the letters of a word or phrase, the resulting anagram must have the same number of characters as the original word or phrase.

Q3. Are there any efficient algorithms to check for anagrams?
The sorting approach mentioned earlier is a common and efficient method to check for anagrams. It has a time complexity of O(n log n), where n is the length of the strings being compared. There are other algorithms, such as using character frequency counters, which have a time complexity of O(n), but they may require additional space.

Q4. Are there any Python libraries or functions available to check for anagrams?
Python does not have a built-in function specifically for checking anagrams. However, you can implement the steps mentioned earlier using standard Python string manipulation functions, such as sorting the characters using the sorted() function and comparing strings for equality using the == operator.

Leave a Reply

Your email address will not be published. Required fields are marked *