我在Grok学习中练习,用Python完成。请问下面的问题和测试用例:
在开始新工作后,您会发现您的工作场所似乎非常多语言。也就是说,很多人似乎能说多种语言。您决定对您的同事进行调查,以找出他们可以说的语言。编写一个程序来输出只能说一种语言的人的名字(他们是单语)。
读入用户的一行或多行输入。每行都是一个空格分隔的同事姓名列表,可以说某种语言。该语言的名称将是第一件事。
第一行输入将始终为英语,您可以假设您工作场所的每个人都会说英语。
以下是您的程序与用户之间的示例交互:
Line: English Tim Nicky James Tara John Ben
Line: German Nicky Tim
Line: Mandarin Tim John
Line:
James is monolingual.
Tara is monolingual.
Ben is monolingual.
您的程序可以按任何顺序输出您的单语同事的姓名。如果没有单语同事,你的程序应该输出Everyone是多语言的!
Line: English Boris Aleksei Dmitry Ivan
Line: Russian Dmitry Ivan Boris Aleksei
Line:
Everyone is multilingual!
我已经走了这么远,但我的代码的问题在于它只适用于1,2,3种语言。如果添加更多语言,则会失败。 代码:
masterList = []
supportedLanguages = []
userInput = input("Line: ")
while userInput != "":
splitUserInput = userInput.split()
temporaryList = []
supportedLanguages.append(splitUserInput[0])
temporaryList.append(splitUserInput[0])
splitUserInput.remove(splitUserInput[0])
temporaryList.append(splitUserInput)
masterList.append(temporaryList)
userInput = input("Line: ")
namesMaster = []
for language in masterList:
languageCopy = language
languageCopy.remove(language[0])
names = set()
for name in languageCopy[0]:
names.add(name)
namesMaster.append(names)
if len(namesMaster) == 1:
result = namesMaster[0]
for name in result:
print(name, " is monolingual.")
elif len(namesMaster) == 2:
result = namesMaster[0].difference(namesMaster[1])
print("Everyone is multilingual!")
else:
result = namesMaster[0].difference(namesMaster[1], namesMaster[2])
for name in result:
print(name, " is monolingual.")
答案 0 :(得分:0)
使用defaultdict
:
设置变量:
from collections import defaultdict
masterList = defaultdict(list)
使用while
循环来循环播放input
,并为每次变量分配true
。
while True:
userInput = input("Line: ")
if len(userInput) > 0:
splitUserInput = userInput.split()
lang = splitUserInput[0]
# Everything after the first element is appended.
for s in splitUserInput[1:]:
masterList[s].append(lang)
else:
break
遍历您的defaultdict
以查看是否有任何键只分配了一个值,如果没有,请打印每个人都是多语言的。
all_multilingual = True
for name, langs in masterList.items():
if len(langs) == 1:
print(name + " is monolingual.")
all_multilingual = False
if all_multilingual:
print("Everyone is multilingual!")
答案 1 :(得分:0)
在此Python Grok练习中,目标是使用集合:
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(b - a) # Difference
print(a ^ b) # Symmetric difference
答案 2 :(得分:0)
仅使用已学到的知识-这就是答案(也是最简单的答案)
monolingual = None
line = input('Line: ')
while line:
line = line.split()
names = set(line[1:])
if monolingual is None:
monolingual = names
else:
monolingual -= names
line = input('Line: ')
if monolingual:
for name in monolingual:
print(name, 'is monolingual.')
else:
print('Everyone is multilingual!')
答案 3 :(得分:0)
line = input("Line: ")
a = set(line.split()[1:])
line = input("Line: ")
while line:
line = set(line.split()[1:])
a = a -line
line = input("Line: ")
if a:
for person in a:
print(person + ' is monolingual.')
else:
print("Everyone is multilingual!")