2017-04-25 170 views
1

我正在为我的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”将打印“正确”。我也必须确保我不允许同一个选项出现多次。

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

+0

看看python内置模块[random](https://docs.python.org/2/library/random.html#random.choice)。 –

回答

0

这里有一对夫妇的事情要考虑:

  1. 作为kiran.koduru提到的,看看使用random module为容易洗牌名单。
  2. 当前您的代码存储收到的正确答案。这使得它很难,因为当答案被洗牌时,存储的答案不再正确。另一种方法是将choicecorrect放在一起,并在之后计算出正确的答案
  3. 您的代码不知道addChoice是否会有更多的选择添加,因此洗牌会导致计算浪费。