Skip to content Skip to sidebar Skip to footer

Monty Hall Simulation Returning 50% Odds?

from random import randint numberOfDoors = 3 success = 0 attempts = 0 while True: try: doors = [0] * numberOfDoors doors[randint(0, numberOfDoors - 1)] = 1

Solution 1:

You're forgetting to reset numberOfDoors (number of doors still closed, right?) back to 3. Since every iteration of the first while True: represents a new game show run, the show starts with all three doors initially closed.

...
while True:
    numberOfDoors = 3
    try:
        doors = [0] * numberOfDoors
        doors[randint(0, numberOfDoors - 1)] = 1
...

Next time, try adding print statements to help you debug. In this case, adding print doors right after you assign a car shows that doors has only two elements after the first iteration.

Solution 2:

I wrote a Monty Hall simulation problem myself a while ago. Maybe it will help you with your code - in particular the comments may be useful:

from __future__ import division
import random

results = [] # a list containing the results of the simulations, either 'w' or 'l', win or lose

count = 0while count <200: #number of simulations to perform
    l = [] 

    prize = random.randint(1, 3) #choose the prize door

    initialchoice = random.randint(1, 3) #make an initial choice (the door the contestant chooses)

    exposed = random.randint(1, 3) #choose the exposed door (the door the host chooses)while exposed == initialchoice or exposed == prize: #make sure exposed is not same as prize or the initial choice
        exposed = random.randint(1, 3)

    if initialchoice != prize:
        results.append('l') #if the initial choice was incorrect, append 'l'else:
        results.append('w') #if the initial choice was correct, append 'w'

    count += 1print'prize door:', prize, 'initial choice:',initialchoice, 'exposed door:',exposed #print the results of the simulationprint

w = 0for i in results:
    if i == 'w':
        w += 1print w/len(results) #fraction of times sticking with the original door was successful

Post a Comment for "Monty Hall Simulation Returning 50% Odds?"