我正在做的是从20个池中生成五个问题。因此,为了生成这五个问题,我使用了随机函数。它在大多数情况下都能正常工作,但有时会在五个问题中重复同样的问题。 在代码正常运行的60%的时间内,它确实会生成随机问题,仅几次将同一问题重复两次。我该如何改善呢?
import random
questions = ["Traditional Maori food cooked in an earth oven: ",
"Type in the Maori word for 'cave': ",
"Something you eat to fill your belly: ",
"What is 'Sun' in Maori: ",
"A challenge laid down in chant and dance: ",
"Visitor or guest: ",
"A gathering, meeting, or assembly: ",
"Funeral ceremony: ",
"If you gave a donation, gift, or contribution, you would have given a...: ",
"Maori word for 'Mountain': ",
"What is 'Water' in Maori: ",
"How do you greet in Maori like 'Hi, G'Day': ",
"'Merry Christmas' in Maori: ",
"Word for 'Winter' in Maori: ",
"'Good Morning' in Maori: ",
"Word 'Family' in Maori: ",
"The most popular sport -'Rugby': ",
"Word in Maori for 'Chicken': ",
"'I am tired' in Maori: ",
"Maori name for 'New Zealand': ",
]
answers = ["hangi", "ana", "kai", "ra", "haka", "manuhiri", "hui",
"tangihanga", "koha", "maunga", "wai", "kia ora",
"meri kirihimete", "takurua", "morena", "whanau", "whutuporo",
"heihei", "hiamoe", "aotearoa"]
print("Welcome to Te Reo Maori Quiz!!!\n")
print("Answer the questions with single Maori Words.(Answers have to be in SMALL CAPS)\n")
x=0 `to store correct answers`
i=0
while i<5 :
d=random.randint(0,19)
user_answer = input(questions[d])
if user_answer.lower() == answers[d] :
print("Correct Answer!")
x=x+1
else :
print("Incorrect Answer. The correct answer is: ",answers[d])
i=i+1
percentage = ((x*100)/5)
print("End of Quiz.\n", "Your Final Score is: ", percentage,"%")
答案 0 :(得分:3)
为什么不重塑示例算法,为什么不直接使用random
模块中的sample()
。您可以执行以下操作来获得5个问题和答案:
from random import sample
q = list(zip(questions, answers))
questions = sample(q, 5)
为您提供五个问题答案对的随机列表:
[(''在土炉中烹制的传统毛利人食物:','hangi'),
(“毛利语中的“圣诞快乐”:”,“ meri kirihimete”),
(“毛利语为“ Mountain”的单词:”,“ maunga”),
(“毛利语中“鸡”的单词:”,“ heihei”),
(“毛利语中的“水”是什么:”,“围”)]
答案 1 :(得分:0)
您可以在循环的末尾添加两行:
del questions[d]
del answers[d]