Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print anagrams together in Python using List and Dictionary
In this tutorial, we will write a program to find and print anagrams together using list and dictionary. Anagrams are words formed by rearranging the letters of another word, like "listen" and "silent".
Algorithm
Here's our step-by-step approach ?
1. Initialize a list of strings.
2. Initialize an empty dictionary.
3. Iterate through the list of strings.
3.1. Sort the string and check if it is present in the dictionary as key or not.
3.1.1. If the sorted string is already present dictionary as a key then, append the original string to the key.
3.2 Else map an empty list with the sorted string as key and append the original to it.
4. Initialize an empty string.
5. Iterate through the dictionary items.
5.1. Concatenate all the values to the empty string.
6. Print the string.
Example with True Anagrams
Let's implement the algorithm with words that are actually anagrams ?
# initializing the list of strings with anagrams
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
# initializing an empty dictionary
anagrams = {}
# iterating through the list of strings
for word in words:
# sorting the string to create a key
key = "".join(sorted(word))
# checking whether the key is present in dict or not
if key in anagrams:
# appending the original string to the key
anagrams[key].append(word)
else:
# mapping a new list to the key
anagrams[key] = [word]
# printing anagram groups
for key, group in anagrams.items():
if len(group) > 1: # only print if there are actual anagrams
print(f"Anagrams: {group}")
Anagrams: ['eat', 'tea', 'ate'] Anagrams: ['tan', 'nat']
Complete Solution
Here's a more comprehensive version that handles the grouping and display ?
def group_anagrams(words):
anagram_dict = {}
for word in words:
# Create key by sorting characters
sorted_word = "".join(sorted(word.lower()))
# Group words with same sorted characters
if sorted_word in anagram_dict:
anagram_dict[sorted_word].append(word)
else:
anagram_dict[sorted_word] = [word]
# Return only groups with more than one word
return [group for group in anagram_dict.values() if len(group) > 1]
# Test with example words
word_list = ["listen", "silent", "elbow", "below", "angel", "glean", "study"]
anagram_groups = group_anagrams(word_list)
print("Anagram groups found:")
for i, group in enumerate(anagram_groups, 1):
print(f"Group {i}: {group}")
Anagram groups found: Group 1: ['listen', 'silent'] Group 2: ['elbow', 'below'] Group 3: ['angel', 'glean']
How It Works
The algorithm uses the key insight that anagrams have the same characters when sorted. For example:
-
sorted("listen")gives['e', 'i', 'l', 'n', 's', 't'] -
sorted("silent")gives['e', 'i', 'l', 'n', 's', 't']
Since both produce the same sorted sequence, we can use this as a dictionary key to group anagrams together.
Conclusion
This approach efficiently groups anagrams using sorted characters as dictionary keys. The time complexity is O(n × m log m) where n is the number of words and m is the average word length.
