Quiz Web app error: Function to generate 10 random questions sometimes generates 9 or 11 questions instead

Quiz Web app error: Function to generate 10 random questions sometimes generates 9 or 11 questions instead

我正在使用 flask 在 pythonanywhere 上编写一个测验应用程序。这是我第一次使用 flask 或 pythonanywhere,所以我还在学习中。下面的函数抛出一个奇怪的错误,有时它会生成 11 或 9 个字典条目而不是 10 个,即使 Qnum 参数永远不会改变。

我认为这个问题可能与别名有关(因为该函数删除了一个条目),所以我尝试通过遍历字典键和值来制作单独的列表。当我直接在主应用程序文件中编写代码时,代码运行良好,但一旦我将其抽象为辅助函数,它就开始运行了。

来自辅助函数文件:

  def create_answer_dict(Dict, Qnum):
        import random
        Qdict={}
        for i in range(Qnum):
            #Choose random word to test
            Qkeys=[]
            for key in Dict.keys():
                Qkeys.append(key)
            Qword=random.choice(Qkeys)

            #Get correct answer from dictionary
            correctAnswer = Dict[Qword]

            #Generate wrong answer options
            wrongAnswers=[]
            for value in Dict.values():
                wrongAnswers.append(value)
            del wrongAnswers[wrongAnswers.index(correctAnswer)]
            wrongAnswers = random.sample(wrongAnswers, 3)
            answerOptions = wrongAnswers + [correctAnswer]
            random.shuffle(answerOptions)
            Qdict[Qword]=answerOptions
        return Qdict

来自主应用程序文件:

@app.route("/", methods=["GET","POST"])
def index():
    Qdict=create_answer_dict(questions, total)
    if request.method == "GET":
        return render_template('main.html', q = Qdict, keys=Qdict.keys())
    elif request.method == 'POST':
        score=0
        for i in Qdict.keys():
            answered=request.form[i]
            if original_questions[i]==answered:
                score+=1
    return render_template("results.html", score=score, total=total)

来自 html 视图:

<form action='/' method='POST'>
    <ol>
        {% for i in keys %}
            <li>What is the French for <u>{{i}}</u> ?  </li>
            {% for j in q[i] %}
                <input type='radio' value='{{j}}' name='{{i}}'      style="margin-right: 5"/>{{j}}
                <br></br>
            {% endfor %}
        {% endfor %}
    </ol>
    <input type="submit" value="submit" />
</form>

它应该如何工作:

可能的问题和答案存储在字典对象中。

在我的主应用程序文件中,我使用我的问答词典和变量总计作为参数,从辅助函数文件中调用此函数。总数设置为 10。

函数选择第Q题,找到对应答案,随机选出3个错误答案。

它将returns这些作为字典,格式如下:

{Question1:[CorrectAnswer, IncorrectAnswer1,IncorrectAnswer2, IncorrectAnswer3],
Question2:[CorrectAnswer, IncorrectAnswer1,IncorrectAnswer2, IncorrectAnswer3], 
etc.}

一切都会返回而不会引发错误,只是有时字典中的条目比预期少一个或多一个。

你不能指望通过从另一个字典中随机选择 n 个条目来获得长度为 n 的字典,因为总是有可能选择重复的条目(并且由于字典键是唯一的,重复的条目将在生成的字典中被覆盖)。

在字典中选择固定数量 n 随机键的更好方法是简单地从字典键创建一个列表,打乱该列表,然后将该列表切片以仅保留第一个n 个元素。

在您的代码中,它看起来像这样:

def create_answer_dict(Dict, Qnum):
    import random
    Qdict={}

    possibleQuestions = list(Dict.keys())
    random.shuffle(possibleQuestions)
    possibleQuestions = possibleQuestions[:Qnum]

    for Qword in possibleQuestions:
        #Get correct answer from dictionary
        correctAnswer = Dict[Qword]

        #Generate wrong answer options
        wrongAnswers = list(Dict.values())
        del wrongAnswers[wrongAnswers.index(correctAnswer)]
        wrongAnswers = random.sample(wrongAnswers, 3)
        answerOptions = wrongAnswers + [correctAnswer]
        random.shuffle(answerOptions)
        Qdict[Qword] = answerOptions
    return Qdict

这将保证生成 Qnum 个独特的问题。

编辑:此外,在 index() 中,为避免用户未回答所有问题时出现 KeyErrors,请替换

for i in Qdict.keys():
        answered=request.form[i]
        ...

for i in request.form:
        answered=request.form[i]
        ...

工作演示:https://repl.it/@glhr/55701832