2017-04-25 174 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是否會有更多的選擇添加,因此洗牌會導致計算浪費。