Examples
- Palindrome Program in Python (Check String is Palindrome or Not)
- Program to Remove Punctuations From String in Python
- Remove a Character from String in Python (Program With Examples)
- Remove Stop Words from String in Python Using NLTK and spaCy
- Program to Sort Words in Alphabetical Order in Python (Arrange in Alphabetic Order)
- How to Sort Strings in Python? (Program With Examples)
- How to Count Vowels in Python String? Vowels Program in Python
- How to Remove Vowels from String in Python? Program With Examples
- How to Convert String to Int or Float in Python? String Parse Program
- How to Convert Float to Int in Python? Program With Examples
- How to Convert Int to String in Python? Program with Examples
- Remove Spaces from String in Python (Trim Whitespace)
- Python Program to Check If Two Strings are Anagram
- How to Capitalize First Letter in Python? String Capitalization Program
- Find All Permutations of String in Python (Programs and Examples)
- Find All Substrings of a String in Python (Programs with Examples)
- Create Multiline String in Python (With & Without New Line)
Python Program to Check If Two Strings are Anagram
In this tutorial, let’s learn and practice the anagrams program in Python and understand how to efficiently determine if two strings are anagrams of each other. This essential skill will greatly enhance your ability to analyze, manipulate, and compare textual data.
Anagrams are words or phrases formed by rearranging the letters of another word or phrase. Checking if two strings are anagrams involves verifying whether they contain the same characters, regardless of their order.
So, here, we will dive into the anagram program in Python, highlighting practical use cases and see insightful examples for better comprehension.
The anagram programs are useful in various scenarios, including:
-
Word Games and Puzzles: Anagrams play a significant role in word games, puzzles, and brain teasers. Being able to identify anagrams allows you to find hidden words, solve crossword clues, and challenge yourself with linguistic conundrums.
-
Text Processing and Data Cleansing: Anagrams are relevant in data preprocessing tasks where ensuring consistency and removing duplicates are essential. By comparing strings for anagram equivalence, you can identify and eliminate redundant or identical entries, improving data quality.
-
Cryptography and Security: Anagram checking techniques have implications in cryptography and security applications. In some encryption algorithms, anagrams may be used as a basis for key generation or message scrambling, highlighting the importance of efficient anagram detection.
To practice and solidify your understanding of anagram checking in Python, we recommend utilizing the online Python compiler by Tutorials Freak. This dynamic platform offers a user-friendly interface, allowing you to write, run, and experiment with Python code directly in your web browser.
Check Two Strings Are Anagram in Python
To check whether two strings are anagrams in Python, you can compare if the two strings have the same set of characters, disregarding the order.
Code
def are_anagrams(str1, str2):
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
return sorted(str1) == sorted(str2)
# Example usage
string1 = "a gentleman"
string2 = "elegant man"
if are_anagrams(string1, string2):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
Output
The strings are anagrams.
Explanation
When you run this program, it will output whether the two strings are anagrams or not.
In the `are_anagrams` function, we remove spaces and convert the strings to lowercase using the `replace()` and `lower()` methods.
Then, we compare the sorted versions of the two strings using the `sorted()` function. If the sorted strings are equal, it means they have the same set of characters and thus are anagrams.
In the example, the strings ‘a gentleman’ and ‘elegant man’ are passed to the `are_anagrams` function. Since they have the same set of characters, the program will output: "The strings are anagrams."
Anagram Program in Python Using for Loop
Here's an anagram program in Python using a for loop to check if two strings are anagrams:
Code
def are_anagrams(str1, str2):
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
if len(str1) != len(str2):
return False
for char in str1:
if char in str2:
str2 = str2.replace(char, "", 1)
else:
return False
return True
# Example usage
string1 = "schoolmaster"
string2 = "the classroom"
if are_anagrams(string1, string2):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
Output
The strings are anagrams.
Explanation
In this version, the are_anagrams function iterates over each character in `str1` using a for loop.
For each character, it checks if it exists in `str2`. If it does, it removes the first occurrence of that character from `str2` using the `replace()` method.
If a character is not found in `str2`, or if the lengths of the two strings are not equal, it returns False. If the for loop completes without any issues, it returns True, indicating that the strings are anagrams.
Anagram Count Program in Python
To count the number of anagrams in a given list of strings in Python, we can create a program that compares each pair of strings and counts the occurrences of anagrams.
Code
from collections import Counter
def count_anagrams(strings):
anagram_count = 0
counts = Counter()
for string in strings:
sorted_string = ''.join(sorted(string))
anagram_count += counts[sorted_string]
counts[sorted_string] += 1
return anagram_count
# Example usage
string_list = ["state", "taste", "inch", "chin", "cat"]
num_anagrams = count_anagrams(string_list)
print(f"The number of anagrams in the list is: {num_anagrams}")
Output
The number of anagrams in the list is: 2
Explanation
In the count_anagrams function, we initialize anagram_count as 0 to keep track of the total number of anagrams. We use the Counter class from the collections module to store the counts of each sorted string.
We iterate over each string in the strings list. For each string, we sort it and convert it back to a string using sorted(). We then use this sorted string as a key to access the count from the counts counter. If the count is non-zero, we increment anagram_count and update the count in the counter by adding 1.
Finally, the function returns the total number of anagrams found.
Anagram Generator Program in Python
To generate anagrams of a given word or string in Python, you can use the itertools.permutations() function to generate all possible permutations of the characters.
Code
from itertools import permutations
def generate_anagrams(word):
anagrams = [''.join(perm) for perm in permutations(word)]
return anagrams
# Example usage
input_word = "tech"
anagram_list = generate_anagrams(input_word)
print(f"Anagrams of '{input_word}':")
for anagram in anagram_list:
print(anagram)
Output
Anagrams of 'tech':
tech
tehc
tceh
tche
thec
thce
etch
ethc
ecth
echt
ehtc
ehct
cteh
cthe
ceth
ceht
chte
chet
htec
htce
hetc
hect
hcte
hcet
Explanation
In the generate_anagrams function, we use permutations(word) to generate all possible permutations of the characters in the given word. Each permutation is converted back into a string using ''.join(perm). These strings are then collected into a list called anagrams, which is returned at the end.
Anagram Program in Python Using Dictionary
Here's an anagram program in Python that uses a dictionary to group anagrams together:
Code
rom collections import defaultdict
def group_anagrams(strings):
anagram_groups = defaultdict(list)
for string in strings:
sorted_string = ''.join(sorted(string))
anagram_groups[sorted_string].append(string)
return list(anagram_groups.values())
# Example usage
string_list = ["angel", "glean", "arc", "car", "inch", "chin"]
anagram_groups = group_anagrams(string_list)
print("Anagram groups:")
for group in anagram_groups:
print(group)
Output
Anagram groups:
['angel', 'glean']
['arc', 'car']
['inch', 'chin']
Explanation
In the group_anagrams function, we create a defaultdict with the list type as the default value. This allows us to group the anagrams together conveniently.
We iterate over each string in the strings list. For each string, we sort it and convert it back to a string using sorted(). We then use this sorted string as a key in the anagram_groups dictionary. We append the original string to the list associated with that key.
Finally, the function returns a list containing all the values (anagram groups) from the anagram_groups dictionary.