python随机洗牌多项选择题

2024-04-20 11:18:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的Python大学课程的琐事问题超类下的多项选择题制作一个子类。选择题方面的工作,但我想洗牌的顺序的答案额外学分。你知道吗

我的一些代码:

class ChoiceQuestion(Question) :
def __init__(self) :
  super().__init__()
  self._choices = []

def addChoice(self, choice, correct) :
  self._choices.append(choice)
  if correct :
     # Convert len(choices) to string.
     choiceString = str(len(self._choices))
     self.setAnswer(choiceString)

# Override Question.display().
def display(self) :
  # Display the question text.
  super().display()

  # Display the answer choices.
  for i in range(len(self._choices)) :
     choiceNumber = i + 1
     print("%d: %s" % (choiceNumber, self._choices[i]))

问题的选择被添加到一个单独的文件中,作为一个测试文件,我无法控制。这是由教授在提交第一个代码的任何变体后运行的。这是他用的。旁注:第二个文件中当然有import语句,但是我已经解决了其他问题,而且很长。不想包括已经解决的东西。你知道吗

print('\n')
mcq = ChoiceQuestion()
mcq.setText("In which country was the inventor of Python born?")
mcq.addChoice("Australia", False)
mcq.addChoice("Canada", False)
mcq.addChoice("Netherlands", True)
mcq.addChoice("United States", False)
for i in range(3) :
    presentQuestion(mcq)

## Presents a question to the user and checks the response.
#  @param q the question
#
def presentQuestion(q) :
   q.display()   # Uses dynamic method lookup.
   response = input("Your answer: ")
   if q.checkAnswer(response):
       print("Correct")
   else:
       print("Incorrect")   # checkAnswer uses dynamic method lookup.

# Start the program.

也就是说,我需要以随机顺序显示选项,同时更新绑定到该选项槽的数值。也就是说,如果荷兰被随机分配到槽1中,输入“1”将打印“正确”。我还必须确保不允许同一选项出现多次。你知道吗

我该怎么办?有什么建议?注意:我只能修改第一个程序


Tags: 文件theselffalselenresponsedef选项
1条回答
网友
1楼 · 发布于 2024-04-20 11:18:56

以下是一些需要考虑的问题:

  1. 作为科杜鲁前面提到过,看看如何使用random module来轻松地洗牌列表。你知道吗
  2. 当前,您的代码在收到正确答案时存储正确答案。这使它变得困难,因为当答案被洗牌时,存储的答案不再正确。另一种方法是将choicecorrect存储在一起,然后计算正确的答案。你知道吗
  3. 您的代码不知道在addChoice中是否会添加更多的选项,因此在那里乱序将导致浪费计算。你知道吗

相关问题 更多 >