pythonanagram

Using Python, find anagrams for a list of words


Suppose I have a list of strings like ["car", "tree", "boy", "girl", "arc"] etc. I want to find groups of anagrams in that list - in this case, (car, arc).

I tried writing code to loop over the list and compare pairs of strings, but how do I account for the fact that the letters can be in a different order?


For the specific case of checking whether a single pair of strings are anagrams of each other, see Checking strings against each other (Anagrams).


Solution

  • In order to do this for 2 strings you can do this:

    def isAnagram(str1, str2):
        str1_list = list(str1)
        str1_list.sort()
        str2_list = list(str2)
        str2_list.sort()
    
        return (str1_list == str2_list)
    

    As for the iteration on the list, it is pretty straight forward