Given an array of words, print all anagrams together ?
Input : arr = ['cat', 'dog', 'tac', 'god', 'act'] Output : 'cat tac act dog god'
This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Approach is very simple :
- Traverse list of strings.
- Sort each string in ascending order and consider this sorted value as Key and original value as Value of corresponding key. Check if key is not present in dictionary that means it is occuring first time,
so map a empty list to Key and append value in it, if key is already present then simple append the value.
- Now each key will contain list of strings which are anagram together.
'cat tac act dog god'
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Counting the frequencies in a list using dictionary in Python
- Python | Removing dictionary from list of dictionaries
- Python | Convert a list of Tuples into Dictionary
- Python | Count number of items in a dictionary value that is a list
- Python | Split dictionary of lists to list of dictionaries
- Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
- Given a sequence of words, print all anagrams together | Set 1
- Given a sequence of words, print all anagrams together | Set 2
- Given a sequence of words, print all anagrams together using STL
- Print all pairs of anagrams in a given array of strings
- Python | Print all sublists of a list
- Python | Remove and print every third from list until it becomes empty
- Python program to print odd numbers in a List
- Python program to print even numbers in a list
- Python program to print negative numbers in a list