Data structures in python: Count Unique Words

I’ve been struggling with this quiz for a bit now. I’ve tried multiple different approaches but haven’t quite figured it out. I reset the code to make it easier to follow any advice that may be given here.

Quiz: Count Unique Words

Your task for this quiz is to find the number of unique words in the text. In the code editor below, complete these three steps to get your answer.

  1. Split verse
    into a list of words. Hint: You can use a string method you learned in the previous lesson.
  2. Convert the list into a data structure that would keep only the unique elements from the list.
  3. Print the length of the container.

verse = "if you can keep your head when all about you are losing theirs and blaming it on you if you can trust yourself when all men doubt you but make allowance for their doubting too if you can wait and not be tired by waiting or being lied about don’t deal in lies or being hated don’t give way to hating and yet don’t look too good nor talk too wise"

`print(verse, '\n')`

`# split verse into list of words`

`verse_list =`

`print(verse_list, '\n')`

`# convert list to a data structure that stores unique elements`

`verse_set =`

`print(verse_set, '\n')`

`# print the number of unique words`

`num_unique =`

`print(num_unique, '\n')`

How would you all approach this and what solutions would you give?

The first step is to split your long string into separate words. To do that, you can use the .split() method. This splits a string into a list of strings, breaking the long string up at whatever character you set as a separator.

"babble on, baby".split("a") --> ["b","bble on, b", "by"]

Once you’ve done that, you need to change the list of words into a list of unique words. Sets are lists that can only contain unique elements. set() converts a list into a set.

set([1, 2, 3, 4, 4, 4, 5, 5]) --> {1, 2, 3, 4, 5}

Then you simply need to count the items in your set; you can use len() for this.

len({1, 2, 3}) --> 3