用python制作多份试卷防止作弊(随机排列题目顺序和答案顺序,提供参考答案)

#! /usr/bin/python
# randomQuizeGenerator.py   -   Creates quizzes with questions and answers in
# random order, along with the answer key.

import random

#The quize data. Keys are states and values are their capitals.
capitals = {'Alabama':'Montgomery', 'Alaska':'Juneau','Arizona':'Phoenix','Arkansas':'Little Rock', 'California':'Sacramento'}

#Generate 3 quiz files.
for quizNum in range(3):
    #Create the quiz and answer key files.
    quizFile = open('capitalsquiz%s.txt'%(quizNum+1),'w')
    answerKeyFile = open('capitalsquiz_answers%s.txt'%(quizNum+1),'w')

    #Write out the header for the quiz.
    quizFile.write('Name: Date: Period: ')
    quizFile.write((' '*20)+'State Capitals Quiz (Form %s)'%(quizNum + 1))
    quizFile.write(' ')

    #Shuffle the order of the states.
    states = list(capitals.keys())
    random.shuffle(states)

    #Loop through all 5 states, making a question for each.
    for questionNum in range(5):
        #Get right and wrong answers:
        correctAnswer = capitals[states[questionNum]]
        wrongAnswers = list(capitals.values())
        del wrongAnswers[wrongAnswers.index(correctAnswer)]
        wrongAnswers = random.sample(wrongAnswers, 3)
        answerOptions = wrongAnswers + [correctAnswer]
        random.shuffle(answerOptions)

        #Write the question and answer options to the quiz file.
        quizFile.write('%s.What is the capital of %s ? '%((questionNum+1),states[questionNum]))
        for i in range(4):
#            quizFile.write('%s %s '%(option[i])%(answerOptions[i]))
            quizFile.write('%s.'%('ABCD'[i]))
            quizFile.write('%s  '%(answerOptions[i]))
        quizFile.write(' ')
        #TODO: Write the answer key to a file
        answerKeyFile.write('%s.%s '%((questionNum+1),'ABCD'[answerOptions.index(correctAnswer)]))
    quizFile.close()
    answerKeyFile.close()

原文地址:https://www.cnblogs.com/guolongnv/p/8136464.html