How to Check if Two Strings are Anagrams in Python 🐍
An anagram is a word or phrase formed by rearranging the letters of another, using all original letters exactly once. For example, “listen” and “silent” are anagrams. Checking if two strings are anagrams is a common task in programming, and Python offers several simple ways to accomplish this.
In this blog post, we’ll explore multiple methods for checking if two strings are anagrams.
What is an Anagram?
An anagram of a string uses all the original letters exactly once and simply rearranges them. To be anagrams, two strings must:
- Contain the same characters
- Have the same frequency of each character
Method 1: Sorting the Strings
The easiest way to check if two strings are anagrams is to sort their characters. If the sorted versions of both strings match, they are anagrams.
Code Example:
# Program to check if two strings are anagrams by sorting
# Step 1: Define a function to check for anagrams
def are_anagrams(str1, str2):
# Step 2: Sort and compare the strings
return sorted(str1) == sorted(str2)
# Step 3: Test the function
string1 = "listen"
string2 = "silent"
print(f"Are '{string1}' and '{string2}' anagrams? {are_anagrams(string1, string2)}")
Explanation:
- Sorting the Strings:
sorted(str1)
andsorted(str2)
return lists of sorted characters for each string. - Comparison: If these sorted lists are equal, the strings are anagrams.
Output:
Are 'listen' and 'silent' anagrams? True
Method 2: Using Counter
from collections
Using Counter
from Python’s collections
module lets us count the frequency of each character and then compare the counts.
Code Example:
# Program to check if two strings are anagrams using Counter
from collections import Counter
# Step 1: Define a function to check for anagrams
def are_anagrams(str1, str2):
# Step 2: Count the characters and compare the counts
return Counter(str1) == Counter(str2)
# Step 3: Test the function
string1 = "triangle"
string2 = "integral"
print(f"Are '{string1}' and '{string2}' anagrams? {are_anagrams(string1, string2)}")
Explanation:
- Counter:
Counter(str1)
andCounter(str2)
count each character in the strings. - Comparison: If both counters are equal, the strings are anagrams.
Output:
Are 'triangle' and 'integral' anagrams? True
Method 3: Using Character Frequency Count
We can manually check if two strings are anagrams by counting each character’s occurrence and comparing these counts.
Code Example:
# Program to check if two strings are anagrams using character frequency count
# Step 1: Define a function to check for anagrams
def are_anagrams(str1, str2):
# Step 2: Check if lengths are equal (early exit if not)
if len(str1) != len(str2):
return False
# Step 3: Create dictionaries for character frequencies
count1 = {}
count2 = {}
# Step 4: Count characters in each string
for char in str1:
count1[char] = count1.get(char, 0) + 1
for char in str2:
count2[char] = count2.get(char, 0) + 1
# Step 5: Compare frequency dictionaries
return count1 == count2
# Step 6: Test the function
string1 = "heart"
string2 = "earth"
print(f"Are '{string1}' and '{string2}' anagrams? {are_anagrams(string1, string2)}")
Explanation:
- Length Check: If the strings don’t have the same length, they aren’t anagrams.
- Frequency Dictionaries:
count1
andcount2
store character counts for each string. - Comparison: If the frequency dictionaries are equal, the strings are anagrams.
Output:
Are 'heart' and 'earth' anagrams? True
Method 4: Using defaultdict
for Character Counting
Using defaultdict
from Python’s collections
module provides an efficient way to handle character counts without manual initialization.
Code Example:
# Program to check if two strings are anagrams using defaultdict
from collections import defaultdict
# Step 1: Define a function to check for anagrams
def are_anagrams(str1, str2):
# Step 2: Check if lengths are equal (early exit if not)
if len(str1) != len(str2):
return False
# Step 3: Create a defaultdict for character frequency
count = defaultdict(int)
# Step 4: Count characters in the first string
for char in str1:
count[char] += 1
# Step 5: Subtract counts using the second string
for char in str2:
count[char] -= 1
if count[char] < 0:
return False
# Step 6: If all values are zero, they are anagrams
return all(value == 0 for value in count.values())
# Step 7: Test the function
string1 = "dusty"
string2 = "study"
print(f"Are '{string1}' and '{string2}' anagrams? {are_anagrams(string1, string2)}")
Explanation:
- Defaultdict for Counting:
defaultdict(int)
initializes counts at zero. - Subtract Counts: We increase counts for
str1
and decrease forstr2
. - All Zeros Check: If all counts are zero, the strings are anagrams.
Output:
Are 'dusty' and 'study' anagrams? True
Conclusion
In this blog, we explored four methods for checking if two strings are anagrams:
- Sorting: Simple and easy-to-read.
- Counter from
collections
: Fast and efficient. - Manual Frequency Count: A straightforward counting approach.
defaultdict
: Streamlined counting with auto-initialization.
Each method has its strengths and may be suitable for different scenarios. Choose the one that fits your needs best, and happy coding! 😊
Stay tuned for more Python programming tutorials and tips!