Search code examples
pythonrandomsimulation

Simulating the outcome of multiple choice test gives unexpected results


I was working on to simulate a problem of probability:

Suppose there is a test containing 180 questions. What is the probability of getting all answers wrong (Test is multiple choice test each question containing 4 choices) (Also consider the fact that the test taker is just guessing)

I tried simulating this problem by using the random module but there is a problem: Most of the time the correct answers would be much larger than the wrong answers. I wanted it to be entirely random including a possibility that the test taker has 100 questions wrong and just 80 questions right.

Is it the problem with my code or is it the problem with the random module (as the random module is a pseudo random number generator).

import random

j = int(input("Enter simulations: "))
n = int(input("Enter no of questions: "))

def event(n):
    L = []
    for i in range(n):
        s = ["C", "W", "W", "W"]
        random.shuffle(s)
        L.append(s)
    return L

def choose(events, n):
    l = []
    m = []
    for i in events:
        l.append(random.choices(i, k=1))
    for k in l:
        for s in k:
            m.append(s)
    return m

def check(p):
    correct = 0
    wrong = 0
    for h in p:
        if h == "W":
            correct += 1
        else:
            wrong += 1
    return correct, wrong

answers = 0
for ghf in range(j):
    p = choose(event(n), n)
    corrects, wrongs = check(p)
    print("Correct answers", corrects, "\n", "Wrong answers", wrongs)
    print()
    if wrongs == 10:
        answers += 1
print("Accuracy", (answers / j) * 100)

Solution

  • You are counting "wrong" answers ("W") as correct and "correct" answers ("C") as wrong. That explains why you are getting so many correct answers by guesswork.

    To fix that, change

    if h == "W":
        correct += 1
    

    to

    if h == "C":
        correct += 1
    

    BTW, the straight answer to "Suppose there is a test containing 180 questions. What is the probability of getting all answers wrong" is (3/4)180 or about 3.24e-23 or 1 in 3.083e22, so it might take rather a long time to get by simulation.