Janet
Janet

Reputation: 11

Monty Hall Python Simulation Calculation

I'm trying to simulate the Monty Hall Problem where someone chooses a door, and a random one is removed--in the end it must be one with a car and one without, one of which someone must have chosen. While I don't need to simulate currently/ask the person using the program which door they'd like, I'm having trouble actually setting up the calculations. When I run the code, it outputs 0, where is should be approximately 66%

import random

doors=[0,1,2]
wins=0

car=random.randint(0,2)
player=random.randint(0,2)

#This chooses the random door removed
if player==car:
    doors.remove.random.randint(0,2)
else:
    doors.remove(car)
    doors.remove(player)

for plays in range(100):
    if car == player:
        wins=wins+1

print(wins) 

Upvotes: 1

Views: 820

Answers (1)

Brendan Abel
Brendan Abel

Reputation: 37509

You need to put your code inside the loop to actually have it run each time. You also need to make sure you're only allowing valid choices the second time (they can't choose the removed door) and that you're only removing valid doors (you can't remove the door with the car or the player-chosen door).

import random

wins = 0

for plays in range(100):
    doors = [0,1,2]
    car = random.choice(doors)
    player = random.choice(doors)

    # This chooses the random door removed
    doors.remove(random.choice([d for d in doors if d != car and d != player]))

    # Player chooses again (stay or switch)
    player = random.choice(doors)
    if player == car:
        wins += 1

print(wins)

But for the purposes of the Monty Hall problem, you don't even have to track the doors.

win_if_stay = 0
win_if_switch = 0
for i in range(100):
    player = random.randint(0, 2)
    car = random.randint(0, 2)
    if player == car:
        win_if_stay += 1
    else:
        win_if_switch += 1

Upvotes: 3

Related Questions