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!

Anagram Program in Python

Last Updated on December 22, 2022 by Prepbytes

An anagram is a condition in which one string or number is rearranged in such a way that each character of the rearranged string or number is part of another string or number. In other words, if the second string is simply a rearrangement of the first, it is said to be an anagram of the first.

For example -The python and yphton are anagrams; Java
and avaJ are anagrams as well.

We will solve this problem before approaching the solution. Let’s understand the problem description.

Problem Description

  • Get the user’s string inputs and store them in different variables.
  • Sort both strings into lists using the sort() technique.
  • Examine both lists to see if they constitute an anagram.
  • Print the result.
  • Exit

Anagram Program Example

def anagramCheck2(str1,str2):  
    # Convert string into lists  
    list1 = list(str1)  
    list2 = list(str2)  
    # Sort the list value  
    list1.sort()  
    list2.sort()  
  
    position = 0  
    matches = True  
  
    while position < len(str1) and matches:  
        if list1[position]==list2[position]:  
            position = position + 1  
        else:  
            matches = False  
  
    return matches  
  
print(anagramCheck2('python','ythonp'))

Output

True

Explanation:
In the above code, we declared the anagramCheck() function, which accepts two strings as arguments. To sort, these strings are turned into a list. The position variable was then defined and assigned a value of zero. The string length is compared to the location value in each iteration of the while loop. Each element in both lists was compared to the other and the position value was incremented by one. When the position value exceeds the string length, the loop is ended and returns true otherwise, it returns false.

Different Anagram Program Techniques

There are few techniques which can be used to find the anagram program in Python.

Counter Technique

In this method, we count the number of characters in both strings. If the count of one string matches the count of another, the matching word is an anagram of another.

Let’s understand the following example.

from collections import Counter, defaultdict  
def checking_anagram(keywords):  
    agrms = defaultdict(list)  
    for i in keywords:  
        hist = tuple(Counter(i).items())  
        agrms[hist].append(i)  
    return list(agrms.values())  
keywords = ("now","own")  
print(checking_anagram(keywords))

Output

[['now'], ['own']]

Explanation:
In the above code, we imported the collection module and its Count and defaultdict methods to check the string’s anagram. Using the counter function, we developed the checking anagram() method to count and record each character. Each count is reduced into a list and tracked. This method is completed for all of the characters in the first string before moving on to the second string. If the counts of both strings match, it indicates that both strings are anagrams.

Reverse Anagram check

We can apply this technique as follows.

words_list = ["cat", "tac", "Play", "ay"]  
anagrams = {}  
for w in words_list:  
    reverse_word=w[::-1]  
    if reverse_word in words_list:  
         anagrams[w] = (words_list.pop(words_list.index(reverse_word)))  
         print(anagrams)

Output

{'cat': 'tac'}

Explanation:
This approach was utilised in the preceding code to compare anagrams among inverted strings. We’ve created two distinct strings here. This approach is similar to palindromes in that we inverted one of the strings and tested it with others. If the strings match, they have produced an anagram, if they do not match, they are not reported as not anagrams.

Position verification Technique:

A position level is compared to a check anagram in this approach. This may be accomplished by comparing the first string’s positional character to each positional character string in the other string. If the first string matches the second string, it is considered an anagram. Let’s have a look at an example.

#Python code to check if two strings are anagrams and palindromes of each other or not
from collections import Counter
def anagrams_check(str1, str2):
    is_anagram = False
    #comparing the frequency of 
    #each character of the string
    if Counter(str1) == Counter(str2):
        #if they have the same frequency then
        #they will be anagrams
        is_anagram = True
        
    if is_anagram:
        if str1 == str2[::-1]:
            return True
        else:
            return False
ans = anagrams_check("abcd","dcba")
print(ans)

Output

True

Explanation:
Another method for obtaining the anagram of the two strings is used in this case. The comparison was also used here. We feed the string into these loops for verification in the nested while loop.

Conclusion:
We Hope this article will help in understanding anagram program in python. Practice more questions like anagram if you are a beginner, as it will increase your logic building as well as the implementation part.

Other Python Programs
Python program to reverse a number
Python program for heap sort
Python program to check armstrong number
Python program to check leap year
Python program to convert celsius to fahrenheit
Python program to find factorial of a number
Python program to reverse a linked list
Python Program to find the middle of a linked list using only one traversal
Python Program to Add Two Numbers
Python Program to Check Palindrome Number
Python Program to Print the Fibonacci Series

Leave a Reply

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