anagrams python 1

anagrams python

from collections import defaultdict

def findAnagrams(input_str):
    anagram = defaultdict(list)

    for word in input_str:
        anagram[str(sorted(word))].append(word)
    return list(anagram.values())

Here is what the above code is Doing:
1. We create a defaultdict with a list as the default value.
2. We iterate over the input list of words.
3. For each word, we sort the letters in the word and use the sorted word as the key in the defaultdict.
4. We append the original word to the list of anagrams for that key.
5. Finally, we return the list of anagrams.

Similar Posts