0

I am using grok learning and I can't seem to get passed this problem. You need to make a program program where you can enter one word at a time, and be told how many unique words you have entered. You should not count duplicates. The program should stop asking for more words when you enter a blank line.

This is my current code:

words = []
word = input("Word: ")
while word != '': 
    words.append(word)
    word = input("Word: ")
print('You know', len(words), 'unique word(s)!')

It counts the amount of words you enter but I can't figure out how to make it check it the word is unique. Here are the desired outputs:

Word: Chat
Word: Chien
Word: Chat
Word: Escargot
Word: 
You know 3 unique word(s)!

Here is another:

Word: Katze
Word: Hund
Word: Maus
Word: Papagei
Word: Schlange
Word: 
You know 5 unique word(s)!
3
  • Use a set, not a list. Commented Oct 17, 2014 at 4:07
  • Please go on, I really need help Commented Oct 17, 2014 at 4:07
  • I think reading about what a set is would be illuminating. Commented Oct 17, 2014 at 4:10

3 Answers 3

3
>>> words = ['Chat', 'Chien', 'Chat', 'Escargot']
>>> set(words)
set(['Chien', 'Escargot', 'Chat'])
>>> "You know " + str(len(set(words))) + " unique word(s)!"
'You know 3 unique word(s)!'
Sign up to request clarification or add additional context in comments.

Comments

0

Use a set if you do not want to store duplicates.

words = set() #initialize a set
word = input("Word: ")
while word != '': 
    words.append(word)
    word = input("Word: ")
print('You know', len(words), 'unique word(s)!')  

If you want to store all the elements irrespective of duplicates, use a list
If you want to find unique elements inside a list, do this:

myset = set(words) #Now, myset has unique elements
print('You know', len(myset), 'unique word(s)!')

Comments

0

Based on what you should have learnt by that point in the course, you can use an if statement to check if the word you're looking at is already in the words list, and only add it if it is not already in the list:

words = []
word = input("Word: ")
while word != '':
  if word not in words:
    words.append(word)
  word = input("Word: ")
print('You know', len(words), 'unique word(s)!')

You'll learn more about sets (which are a more efficient way to solve this question) later in the course.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.