Python Program to Check If Two Strings are Anagram

Spread the love

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. To check if two strings are anagrams, one needs to compare the strings to see if they contain the exact same set of characters. A python program can be an efficient way to determine if two strings are anagrams of each other. In this extensive guide, we will explore multiple ways to achieve this, considering various scenarios and constraints.

Method 1: Using Sorting

A straightforward way to check if two strings are anagrams is to sort the strings and compare them. If they are identical post-sorting, then they are anagrams.

def are_anagrams(str1, str2):
    return sorted(str1) == sorted(str2)

# Example
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2))

Method 2: Using Counter from Collections Module

The Counter class from the collections module can also be used to check if two strings are anagrams by comparing the count of each character in the strings.

from collections import Counter

def are_anagrams(str1, str2):
    return Counter(str1) == Counter(str2)

# Example
str1 = "triangle"
str2 = "integral"
print(are_anagrams(str1, str2))

Method 3: Using Dictionary

If you want to avoid using built-in functions or libraries, you can create a dictionary to store the frequency of each character and compare the dictionaries.

def are_anagrams(str1, str2):
    dict1 = {}
    dict2 = {}
    
    for char in str1:
        dict1[char] = dict1.get(char, 0) + 1
    
    for char in str2:
        dict2[char] = dict2.get(char, 0) + 1
    
    return dict1 == dict2

# Example
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2))

Method 4: Count and Compare

An alternative approach is to create arrays representing the count of each character in the strings and then compare these arrays.

def are_anagrams(str1, str2):
    count1 = [0] * 26
    count2 = [0] * 26
    
    for i in range(len(str1)):
        pos = ord(str1[i]) - ord('a')
        count1[pos] = count1[pos] + 1
    
    for i in range(len(str2)):
        pos = ord(str2[i]) - ord('a')
        count2[pos] = count2[pos] + 1
    
    j = 0
    still_ok = True
    while j < 26 and still_ok:
        if count1[j] == count2[j]:
            j = j + 1
        else:
            still_ok = False
    return still_ok

# Example
str1 = "listen"
str2 = "silent"
print(are_anagrams(str1, str2))

Handling Case and Spaces

In practical scenarios, the strings may contain uppercase letters and spaces, which should be handled appropriately while comparing.

def are_anagrams(str1, str2):
    str1 = str1.replace(' ', '').lower()
    str2 = str2.replace(' ', '').lower()
    return sorted(str1) == sorted(str2)

# Driver Code
str1 = "The Morse Code"
str2 = "Here Come Dots"
print(are_anagrams(str1, str2))

Conclusion

Checking whether two strings are anagrams is a fundamental problem that can be solved using various methods in Python. Depending on the specific needs, constraints, and preferences, one might choose to implement it using sorting, the Counter class from the collections module, dictionaries, or arrays. Handling of cases and spaces is also crucial in real-world scenarios, ensuring the accuracy of the anagram check.

Leave a Reply