Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Using sets to compute unique elements
6. Anagrams again
Set operations
Simulating machines
Summary

Instruction

Very well done! Let's try an additional exercise before moving on.

Exercise

In the previous part, you wrote a function which returned a dictionary of anagrams. Now we will count how many "anagram classes" there are.

In case you don't remember, anagrams are words which contain the same letters in different orders. Write a function called count_anagrams(words) that accepts a list of words (strings) and returns the number of different anagram classes in the list.

For example, for the input

['bacd', 'bcad', 'bcda', 'adf']

the correct output is 2.

The words 'bacd', 'bcad' and 'bcda' are anagrams, so they count as one "anagram class". The word 'adf' is not their anagram, so it belongs to a different class.

The simplest way to solve this exercise is to use sets. For each word in the list, compute its canonical anagram (e.g. its letters sorted in alphabetical order) and add them to the set. Then return the number of elements in the set.

Stuck? Here's a hint!

To quickly sort letters in a string alphabetically and get a new ordered string, use the following code:

''.join(sorted(word))