In this tutorial, you will learn the writing python program to check given two strings are anagrams or not.
Creating an anagram checker program in Python involves comparing two strings to check if they are anagrams of each other, means if one string can be rearranged to form the other.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
For example
“listen” and “silent” are anagrams.
This can be achieved through various methods in Python, catering to different levels of complexity and efficiency. Here are several approaches, ranging from straightforward to more advanced, including brief explanations and code samples:
Read This : What is Anagram? Write an anagram program in C.
How this Python Program will behave?
This Python Program will take two String from user as an input. And after the comparison of two input string, program will return output.
If the string is anagram then Program will return “Given Strings are anagram”.
And if Strings are not anagram then it will return “Strings are not anagram”.
Anagrams Program in Python
Program 1: Basic Anagram Check Using Sorting
One of the simplest ways to check if two strings are anagrams is to sort the characters in each string and then compare them.
In Python, a basic program to check if two words are anagrams can be made using the sorting method. First, the program takes two words and checks if they are the same length. If they aren’t, the program says they’re not anagrams. If they are the same length, the program turns each word into a list of letters and sorts them. Then, it turns the lists back into words. If the sorted words are the same, then the two words are anagrams. This method is simple because all it does is sort the letters and compare them. It works well for checking anagrams in a straightforward and understandable way.
Program
def anagram_check(str1, str2):
if len(str1) != len(str2):
return False
if (sorted(str1) == sorted(str2)) :
return True
else :
return False
str1 = input("Please enter String 1 : ")
str2 = input("Please enter String 2 : ")
if anagram_check(str1,str2):
print("Anagram")
else:
print("Not an anagram")
Output:
Please enter String 1 : python Please enter String 2 : thonpy Anagram
Program 2: Anagram Check by Counting Characters
This method involves counting the frequency of each character in both strings and then comparing these frequencies.
In below Python program we are importing the Counter
class from the collections module. Counter
is a specialized dictionary used for counting hashable objects. It’s an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. The function is_anagrams
takes two parameters, str1
and str2
. Inside the function, it utilizes the Counter
to tally the count of each character in both strings.
The core logic of the function is the expression Counter(str1) == Counter(str2)
. This works by creating a Counter
object for each string, which counts the frequency of each character in the strings. The ==
operator then compares these two Counter
objects.
- If both strings contain exactly the same characters with the same frequencies, the two
Counter
objects will be equal, and the function will returnTrue
, indicating that the strings are anagrams. - If the strings differ in either the characters present or the frequency of any character, the
Counter
objects will not be equal, and the function will returnFalse
.
Program
from collections import Counter
def is_anagrams(str1, str2):
return Counter(str1) == Counter(str2)
# Example usage:
print(is_anagrams("quescol", "colques"))
print(is_anagrams("hello", "python"))
Output
True
False
Program 3: Finding All Anagrams from a List
If you want to find all anagrams of a word from a given list of words, you can use the sorting method combined with a list comprehension.
Program
def check_anagrams(word, candidates):
sorted_word = sorted(word)
return [w for w in candidates if sorted(w) == sorted_word]
string_list = ["colques", "google", "uescolq", "hcl"]
print(check_anagrams("quescol", string_list))
Output
['colques', 'uescolq']
Program 4: Grouping Anagrams
If you need to group a list of words into anagrams, you can use a dictionary to map the sorted characters to their corresponding words.
from collections import defaultdict
def anagrams_grouping(words):
anagram_map = defaultdict(list)
for word in words:
key = tuple(sorted(word))
anagram_map[key].append(word)
return list(anagram_map.values())
string_list = ["colques", "hello", "uescolq", "act", "ohlel", "cta"]
print(anagrams_grouping(string_list))
Output
[['colques', 'uescolq'], ['hello', 'ohlel'], ['act', 'cta']]
Hope above program helped you to learn writing Anagrams Program in Python.