简体   繁体   中英

How to choose a random question from items in a list/dict imported from a CSV file?

I have to code a quiz as a homework assignment. The very last step involves me randomizing the order in which the questions are asked.

I'm not sure how to do this, because I'm not 100% sure even how my existing code works - whether to pick it from the CSV file itself or from the list/dict (is it a list or a dictionary?).

score=0
questionno=0
def parse_csv(file_name: str) -> dict:
    retval = {}
    with open(file_name) as f:
        for line in f:
            data = line.strip().split(',')
            key, *values = (v.strip() for v in data)
            retval[key] = values
    return retval

questions = parse_csv('questions.txt')
for question, answers in questions.items():
    questionno+=1
    correct = answers[-1]
    answers = answers[:-1]
    print(questionno)
    result = input(f"{question}: {','.join(answers)}")
    if result=="A" or result=="B" or result=="C" or result=="D":
        if result == correct:
            print('Correct!')
            score+=1
        else:
            print(f'The correct answer is {correct!r}')
            break
    else:
        print("Invalid Entry")
        break

print(score)

By design, dictionnaries in Python don't have any order (see OrderedDict for that), but when you iterate over it the order isn't really random either!

Here's what I suggest to make the question order truly random:

from random import shuffle


questions = parse_csv('questions.txt')
shuffledquestions = list(questions.items())
shuffle(shuffledquestions)
for (question, answer) in shuffledquestions:
    questionno+=1
    correct = answers[-1]
    answers = answers[:-1]
    print(questionno)
    result = input(f"{question}: {','.join(answers)}")
    if result=="A" or result=="B" or result=="C" or result=="D":
        if result == correct:
            print('Correct!')
            score+=1
        else:
            print(f'The correct answer is {correct!r}')
            break
    else:
        print("Invalid Entry")
        break

The idea is making a list of (question, answer) Tuple, shuffle it using random.shuffle and then iterate over it.

EDIT: I forgot that shuffle() was in place and didn't return the list, now it should work

It is a dictionary. You could use numpy.random.shuffle after converting dictionary to list of tuples like so:

import numpy as np

questions = list(parse_csv('questions.txt').items())
np.random.shuffle(questions)
for question, answers in questions:
    ...

You can ask the question again if the user enters invalid entry - Also it shuffles the order.

import random
score=0
questionno=0
def parse_csv(file_name: str) -> dict:
    retval = {}
    with open(file_name) as f:
        for line in f:
            data = line.strip().split(',')
            key, *values = (v.strip() for v in data)
            retval[key] = values
    return retval
questions = parse_csv('questions.txt')
l = list(questions.items())
random.shuffle(l)
questions = dict(l)
for question, answers in questions.items():
    questionno+=1
    correct = answers[-1]
    answers = answers[:-1]
    while True:    
        result = input(f"{question}: {','.join(answers)}")
        if result=="A" or result=="B" or result=="C" or result=="D":
            if result == correct:
                print('Correct!')
                score+=1
                break
            else:
                print(f'The correct answer is {correct!r}')
                break
        else:
            print("Invalid Entry\n Try again...")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM