Open In App

Print anagrams together in Python using List and Dictionary

Last Updated : 27 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of words, print all anagrams together. 

Examples:

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 occurring 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.

Implementation:

Python3




# Function to return all anagrams together
def allAnagram(input):
     
    # empty dictionary which holds subsets
    # of all anagrams together
    dict = {}
 
    # traverse list of strings
    for strVal in input:
         
        # sorted(iterable) method accepts any
        # iterable and returns list of items
        # in ascending order
        key = ''.join(sorted(strVal))
         
        # now check if key exist in dictionary
        # or not. If yes then simply append the
        # strVal into the list of it's corresponding
        # key. If not then map empty list onto
        # key and then start appending values
        if key in dict.keys():
            dict[key].append(strVal)
        else:
            dict[key] = []
            dict[key].append(strVal)
 
    # traverse dictionary and concatenate values
    # of keys together
    output = ""
    for key,value in dict.items():
        output = output + ' '.join(value) + ' '
 
    return output
 
# Driver function
if __name__ == "__main__":
    input=['cat', 'dog', 'tac', 'god', 'act']
    print (allAnagram(input))


Output

cat tac act dog god 

Time Complexity: O(n), where n is the total number of the characters in the given input.
Auxiliary Space: O(n)



Similar Reads

Given a sequence of words, print all anagrams together using STL
Given an array of words, print all anagrams together. For example, Input: array = {“cat”, “dog”, “tac”, “god”, “act”}output: cat tac act, dog godExplanation: cat tac and act are anagrams and dog and god are anagrams as they have the same set of characters.Input: array = {“abc”, “def”, “ghi”}output: abc, def, ghiExplanation: There are no anagrams in
10 min read
Given a sequence of words, print all anagrams together | Set 2
Given an array of words, print all anagrams together. For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”. Recommended PracticePrint Anagrams TogetherTry It! We have discussed two different methods in the previous post. In this post, a more efficient solution is discussed.Trie data struct
13 min read
Given a sequence of words, print all anagrams together | Set 1
Given an array of words, print all anagrams together. For example, if the given array is {"cat", "dog", "tac", "god", "act"}, then output may be "cat tac act dog god". Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. A simple method is to create a Hash Table. Calculate the hash value of each word in such a way th
15+ min read
Print all pairs of anagrams in a given array of strings
Given an array of strings, find all anagram pairs in the given array. Example: Input: arr[] = {"geeksquiz", "geeksforgeeks", "abcd", "forgeeksgeeks", "zuiqkeegs"}; Output: (geeksforgeeks, forgeeksgeeks), (geeksquiz, zuiqkeegs) We can find whether two strings are anagram or not in linear time using count array (see method 2 of this). One simple idea
13 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python | Group Anagrams from given list
Anagrams are words that are formed by similar elements but the orders in which these characters occur differ. Sometimes, we may encounter a problem in which we need to group the anagrams and hence the solution to the above problem always helps. Let's discuss certain ways in which this can be done. Method #1 : Using defaultdict() + sorted() + values
7 min read
Print n 0s and m 1s such that no two 0s and no three 1s are together
Given two integers n and m where n is the number of 0s and m is the number of 1s. The task is to print all the 0s and 1s in a single row such that no two 0s are together and no three 1s are together. If it's not possible to arrange 0s and 1s according to the condition then print -1.Examples: Input: n = 1, m = 2 Output: 011Input: n = 4, m = 8 Output
6 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python Program For Rearranging A Linked List Such That All Even And Odd Positioned Nodes Are Together
Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1->2->3->4 Output: 1->3->2->4 Input: 10->22->30->43->56->70 Output: 10->30->56->22->43->70Recommended: Please solve it on "PRACTICE" first, before moving on to the
6 min read
Print consecutive characters together in a line
Given a sequence of characters, print consecutive sequence of characters in a line, otherwise print it in a new line. Examples: Input : ABCXYZACCD Output : ABC XYZ A C CD Input : ABCZYXACCD Output: ABC ZYX A C CD The idea is to traverse string from left to right. For every traversed character, print it in a line if it is consecutive to previous one
3 min read
three90RightbarBannerImg