Reputation: 51
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)!
Upvotes: 0
Views: 257
Reputation: 1
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.
Upvotes: 0
Reputation: 23095
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)!')
Upvotes: 0
Reputation: 4563
>>> 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)!'
Upvotes: 3