Using Python, find anagrams for a list of words

user1040563 picture user1040563 · Nov 27, 2011 · Viewed 105.8k times · Source

If I have a list of strings for example:

["car", "tree", "boy", "girl", "arc"...]

What should I do in order to find anagrams in that list? For example (car, arc). I tried using for loop for each string and I used if in order to ignore strings in different lengths but I can't get the right result.

How can I go over each letter in the string and compare it to others in the list in different order?

I have read several similar questions, but the answers were too advanced. I can't import anything and I can only use basic functions.

Answer

Ofir Farchy picture Ofir Farchy · Nov 27, 2011

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