Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grok learning- "How many words"

Tags:

python

I'm doing a question on grok learning, it asks for this:

You are learning a new language, and are having a competition to see how many unique words you know in it to test your vocabulary learning.

Write a 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.

For example:

Word: Chat 
Word: Chien   
Word: Chat   
Word: Escargot
Word: 

You know 3 unique word(s)!

​and

Word: Katze    
Word: Hund   
Word: Maus  
Word: Papagei   
Word: Schlange 
Word: 

You know 5 unique word(s)!

and

Word: Salam   
Word: 

You know 1 unique word(s)!

I cannot get it to work when there are multiple duplicates, here is my code:

word = input("Word: ")
l = []
l.append(word)
words = 1
while word != "":
    if word in l:
        word = input("Word: ")
    else:
        words = 1 + words
        word = input("Word: ")
print("You know " + str(words) , "unique word(s)!" )
like image 846
beginner Avatar asked Dec 05 '25 14:12

beginner


1 Answers

Using a set this problem can be solved easily:

l = set()
while True:
    new_word = input("Word:")
    if new_word=="":
        break
    l.add(new_word)
print("You know " + str(len(l)) , "unique word(s)!" )

This is a good example for the power of the Python standard library. Usually if you have a problem there already is a good solution in it.

like image 104
Benjamin Avatar answered Dec 07 '25 07:12

Benjamin