Python Anagram: Python Program to Check if Two Strings are Anagram

In this tutorial, we will learn Python Anagram and how we can Check if Two Strings are Anagram. But first, we should familiar with the anagram’s concept.

What is Anagram?

A situation in which one string or number is rearranged in such a way that each character of the rearranged string or number must be a component of another string or number is known as an anagram. In other words, if the second string is a simple rearrangement of the first, it is said to be an anagram of the first. For example, the words python and yphton are anagrams, as are Java and avaJ.

Now Let’s have a look at some code examples of Anagram.

Example 01: Python Anagram Using sorted() function

Python has an inbuilt method called sorted() that produces a sorted string without changing the original text.

The Python implementation of the above method is as follows:


# 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:

Anagram Using sorted function

Example 02: Python Anagram Using Counter() function

  • Count all the frequencies of 1st string and 2 and using a counter()
  • If they are equal then print anagram
# 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 = "triangle"
s2 = "integral"
check(s1, s2)

Output:

Anagram Using Counter function

Conclusion of Python Anagram

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. Palindrome in Python

FAQs

Do anagrams have to be real words?

Is it necessary for anagrams to be genuine words? Both yes and no! Anagrams must make sense, although they can include names or locations in addition to “proper words.” Nonsense words aren’t usually regarded as “good form” in an anagram because one of the most important aspects of an anagram is its coherence of meaning.

Why are anagrams important?

Anagrams and Their Importance Anagrams have been employed for strange, significant, and hidden names since the third century BCE. They are still used in ordinary speech and writing today. Anagrams can be played as a simple game for entertainment or as a kind of mental practice.

Leave a Comment