Python Program to Find Anagram
An anagram is a word or phrase that results from rearranging the letters of one word or phrase to target another one, using every original letter exactly once. For instance, “listen” and “silent”.
This is to write down the Python program that tells whether two strings are anagrams, along with a description of each part in minute details.
Python Program:
def is_anagram(str1, str2):
# Remove spaces and convert to lowercase
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# Check if the sorted versions of the strings are the same
return sorted(str1) == sorted(str2)
# Input strings
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")
# Check if they are anagrams
if is_anagram(word1, word2):
print(f'"{word1}" and "{word2}" are anagrams.')
else:
print(f'"{word1}" and "{word2}" are not anagrams.')
Step-by-Step Explanation:
1. Function Definition:
def is_anagram(str1, str2):
- We define a function
is_anagramthat takes two strings (str1andstr2) as input arguments.
2. Preprocessing:
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
- Elimination of spaces:
str1.replace(" ", "")removes all spaces fromstr1. Similarly, all spaces instr2are removed. It is ensured that spaces do not affect the comparison. - Convert to lowercase:
.lower()converts all characters to lowercase to ensure the comparison is case-insensitive (for example, “Listen” and “Silent” should match).
3. Sorting:
return sorted(str1) == sorted(str2)
sorted()function: This function takes an iterable (like a string) and returns a sorted list of its characters.- For example:
sorted("listen")→['e', 'i', 'l', 'n', 's', 't']sorted("silent")→['e', 'i', 'l', 'n', 's', 't']
- If the sorted lists of characters for both strings are equal, the strings are anagrams.
4. Input and Output:
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")
input()is used to get input from the user. These are the words we want to check for being anagrams.
5. Conditional Check:
if is_anagram(word1, word2):
print(f'"{word1}" and "{word2}" are anagrams.')
else:
print(f'"{word1}" and "{word2}" are not anagrams.')
- The
is_anagramfunction returnsTrueorFalse. Based on this result, the program prints whether the words are anagrams or not.
Example Run:
Input:
Enter the first word: listen
Enter the second word: silent
Output:
"listen" and "silent" are anagrams.
How It Works:
1. Input Strings:
- User gives two strings.
2. Preprocessing:
- Both the strings are converted to lower case and the spaces are removed.
3. Sorting:
- Characters in each string are sorted and compared.
4. Result:
- If the sorted lists are equal, the strings are anagrams; otherwise, they are not.
Alternative Approaches:
Using a Dictionary (Frequency Count):
Instead of sorting, you can count the frequency of each character in both strings and compare the counts:
from collections import Counter
def is_anagram(str1, str2):
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
return Counter(str1) == Counter(str2)
# Input strings
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")
if is_anagram(word1, word2):
print(f'"{word1}" and "{word2}" are anagrams.')
else:
print(f'"{word1}" and "{word2}" are not anagrams.')
Counterfromcollections: This creates a frequency dictionary for the characters in a string.- For example:
Counter("listen")→{'l': 1, 'i': 1, 's': 1, 't': 1, 'e': 1, 'n': 1}Counter("silent")→{'s': 1, 'i': 1, 'l': 1, 'e': 1, 'n': 1, 't': 1}
- If the frequency dictionaries are the same, the strings are anagrams.
Which Method is Better?
- Sorting is fairly straightforward and intuitive, but for larger strings, this is less efficient (O(n log n)).
- Frequency Count (using
Counter) is faster for large inputs (O(n)) and should be preferred in performance-intensive applications.