Python Program to Check Anagram
An anagram is a word or phrase formed by rearranging the letters of another word. Checking anagrams is a common string problem in Python.
In this tutorial, we will explore different methods to check whether two strings are anagrams.
1. Understanding the Problem
Given two strings, check if they are anagrams of each other.
Input: listen, silent Output: True
2. Method 1: Using Sorting
str1 = input("Enter first string: ").replace(" ", "").lower()
str2 = input("Enter second string: ").replace(" ", "").lower()
if sorted(str1) == sorted(str2):
print("Anagram")
else:
print("Not Anagram")
If sorted characters of both strings are equal, they are anagrams.
3. Method 2: Using Dictionary
def char_count(s):
count = {}
for char in s:
count[char] = count.get(char, 0) + 1
return count
str1 = input().replace(" ", "").lower()
str2 = input().replace(" ", "").lower()
if char_count(str1) == char_count(str2):
print("Anagram")
else:
print("Not Anagram")
This method compares character frequencies using dictionaries.
4. Method 3: Using collections.Counter
from collections import Counter
str1 = input().replace(" ", "").lower()
str2 = input().replace(" ", "").lower()
if Counter(str1) == Counter(str2):
print("Anagram")
else:
print("Not Anagram")
Counter makes the frequency comparison simple and efficient.
5. Method 4: Using Function
def is_anagram(s1, s2):
return sorted(s1.replace(" ", "").lower()) == sorted(s2.replace(" ", "").lower())
print(is_anagram("listen", "silent"))
Functions make the code reusable and clean.
6. Method 5: Without Built-in Functions
str1 = input().replace(" ", "").lower()
str2 = input().replace(" ", "").lower()
if len(str1) != len(str2):
print("Not Anagram")
else:
for char in str1:
if str1.count(char) != str2.count(char):
print("Not Anagram")
break
else:
print("Anagram")
This method manually compares character counts without using advanced tools.
7. Algorithm
1. Take two input strings.
2. Remove spaces and convert to lowercase.
3. Compare sorted strings or frequency counts.
4. If equal, strings are anagrams.
5. Print result.
8. Common Mistakes
1. Ignoring spaces and case sensitivity.
2. Not checking string length first.
3. Incorrect frequency comparison.
4. Using inefficient logic unnecessarily.
9. Applications
1. Word games.
2. Spell checking systems.
3. Cryptography.
4. NLP applications.
Conclusion
Checking anagrams is a popular string problem that improves your understanding of sorting and hashing techniques.
Using Counter or sorting is the most efficient approach, while manual methods strengthen problem-solving skills.
Codecrown