gpt4 book ai didi

python - 神交学习- "How many words"

转载 作者:行者123 更新时间:2023-12-04 17:50:42 26 4
gpt4 key购买 nike

我在做一个关于 grok learning 的问题,它要求这样的:

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

当有多个重复时我无法让它工作,这是我的代码:

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

最佳答案

使用集合可以很容易地解决这个问题:

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

这是 Python 标准库强大功能的一个很好的例子。通常,如果您遇到问题,已经有很好的解决方案。

关于python - 神交学习- "How many words",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45234122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com