Solution: Group Anagrams
Here's a detailed analysis on how to solve the Group Anagrams problem.
We'll cover the following...
Solution: using dictionary and list
def anagrams(lst):"""Function to find anagram pairs:param lst: A lst of strings:return: Group of anagrams"""# Empty dictionary which holds subsets of all anagrams togetherdictionary = {}# traversing all the lst stringsfor string in lst:# sorting the lst string and storing it in a keykey = ''.join(sorted(string))# if the key is already in the dictionary then appending the original lst(Anagram).if key in dictionary.keys():dictionary[key].append(string)else: # If there is no key in the dictionarydictionary[key] = []dictionary[key].append(string)# traversing the whole dictionary and concatenating values and keysresult = []for key, value in dictionary.items():if len(value) >= 2:result.append(value)result = sorted(result) # sort the listreturn result# Driver to test above codeif __name__ == '__main__':lst = ['tom marvolo riddle ', 'abc', 'def', 'cab', 'fed', 'clint eastwood ', 'i am lord voldemort', 'elvis', 'old west action', 'lives']print (anagrams(lst))
Explanation
This solution sorts each input string in an ascending order, considers it as a key and the ...
Access this course and 1400+ top-rated courses and projects.