简体   繁体   中英

Grok learning- “How many words”

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)!" )

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.

There is also a way where you do not necessarily have to use the set() function. But it is still best if you learn about the set() function anyway.

Here's the code that doesn't need a set() function, but still works fine:

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)!')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM