python - 自动化无聊的事情 : Random Quiz Generator

标签 python python-3.x

我一直在遵循教程书中的一个示例程序,该程序是使用一本包含美国所有 50 个州及其首府的字典,然后创建一组随机的多项选择 A-D 问题,然后将这些问题随机的 3 个不同的测验打印成 3 个不同的文件。然后,每个测验的所有问题的答案都会打印到答案文件中,与每个问题文件一起使用。

作为测试,我目前仅使用 5 的范围进行测试。当我运行该程序时,程序按预期工作,只是为每个测试仅创建 25 个问题/答案组合,而不是 50 个。

我检查了好几遍,还是不明白这是为什么。任何意见将不胜感激,谢谢。

# randomQuizGenerator.py - Creates quizzes with questions and answers in
# random order, along with the answer key.

import random

capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
        'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
        'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
        'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
        'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
        'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
        'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
        'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
        'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
        'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton',
        'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
        'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
        'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
        'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
        'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
        'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia',
        'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}

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

    # Write out the header for the quiz.
    quizFile.write('Capitals Quiz #%s' % (quizNum+1) + '\nName:\nDate:\n\n')
    quizFile.write('What is the capital of:\n')
    answerFile.write('Capitals Quiz %s' % (quizNum+1) + '\n\n')

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

    # Loop through all 50 states, making a question for each.
    # set question number = 0
    q_num = 0
    for st in states:
        # question number increase
        q_num += 1
        random.shuffle(states)

        # unused needed for choosing 3 incorrect options
        unusedStates = states

        # write question number and state name (QUESTION)
        quizFile.write('Q%s: ' % q_num + st + '?\n')

        # create answer options list and fill with 1 correct answer + 3 incorrect ones
        answerOptions = [None] * 3
        answerOptions.append(capitals[st])
        # remove correct answer to avoid duplication
        unusedStates.remove(st)
        for Opt in range(0, 3):
            curr_ans = unusedStates[Opt]
            answerOptions[Opt] = capitals[curr_ans]
        # randomise answer list
        random.shuffle(answerOptions)
        # write answers
        for i in range(0, 4):
            quizFile.write(answerOptions[i]+'   ')
        quizFile.write('\n')

        # write correct answer in answer file
        answerFile.write(capitals[st]+'\n')

    quizFile.close()
    answerFile.close()

最佳答案

发生这种情况的原因是您在迭代集合时修改了集合:

states = [1,2,3,4,5,6,7,8,9,10]
for st in states:
    print(st)
    states.remove(st)

此片段将打印出来:

1
3
5
7
9

您尝试过的是:

unusedStates = states
unusedStates.remove(st)

但这不会复制列表。它只会为同一个列表创建另一个名称。

这是一个略有更改的版本,但我绝不是“Python 专业人士”。

import random

capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
            'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
            'Connecticut': 'Hartford'}
states = list(capitals.keys())

random.shuffle(states)

# Loop through all 50 states, making a question for each.

for idx, state in enumerate(states):
    # use this for 1-based humans
    q_num = idx + 1

    # the 49 other states
    other_states = states[:idx] + states[idx+1:]
    # pick 3 states (guaranteed to be unique)
    answer_states = random.sample(other_states, 3)
    # add the correct one
    answer_states.append(state)

    # convert states to capitals
    answer_options = [capitals[st] for st in answer_states]

    # randomise answer list
    random.shuffle(answer_options)

    print('Question %s about %s' % (q_num, state))
    print('Options', answer_options)
    print('Correct Answer', capitals[state])
    print() #empty line

请注意使用 random.sample 来选择 3 个唯一选项,使用 enumerate 使用索引变量迭代列表。

另请注意使用“切片”创建 49 个元素的列表。

关于python - 自动化无聊的事情 : Random Quiz Generator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52903910/

相关文章:

python - Pandas unstack 问题 : ValueError: Index contains duplicate entries, 无法 reshape

python - 在 Python 中将 datetime.datetime 对象转换为自纪元以来的天数

python - 从另一个应用程序内部调用 Pyramid 框架应用程序

python - 将浮点四舍五入到一位小数(具体问题)

ubuntu - 在 Ubuntu 上为 Python3 安装 mod_wsgi

python - 计算椭圆内的点

python - 在python中将文本写入zipfile

python - GNU Parallel 替换管道 xargs -n 1

python - 使用 issubset 比较两个 pandas 数据框列之间的设置值

python - 为什么调用 super().foo 和 super().__getattribute__ ("foo"之间有区别)