SharedNew Projects and Problems / Monty Hall.ipynbOpen in CoCalc
Author: Peter Francis

Monty Hall Simulation

In [1]:
import random as rd
In [2]:
def run(V = 'Q'): # create door scheme doors = [False,False,False] # place car car = rd.randint(0,2) doors[car] = True if V !='Q': print(f'doors are {doors}') # contestant chooses door firstChoice = rd.randint(0,2) if V !='Q': print(f'contestant chooses {firstChoice}') # monty chooses a door to open possibleToReveal = [door for door in [0,1,2] if door not in [car, firstChoice]] montyOpens = possibleToReveal[rd.randint(0,len(possibleToReveal)-1)] if V !='Q': print(f'monty opens {montyOpens}') # contestant chooses to switch or stay movement = ['switch', 'stay'][rd.randint(0,1)] if V !='Q': print('contestant chooses to ' + movement + ' so is at ', end='') # contestant gets the new location possibleToSwitchTo = [door for door in [0,1,2] if door not in [montyOpens, firstChoice]][0] finalChoice = {'switch': possibleToSwitchTo, 'stay':firstChoice}[movement] if V !='Q': print(f'{finalChoice}') # contestant gets their prize prize = doors[finalChoice] if V !='Q': if prize: print('contestant wins') else: print('contestant loses') return (movement, prize)
In [3]:
run('V')
doors are [True, False, False] contestant chooses 1 monty opens 2 contestant chooses to switch so is at 0 contestant wins
('switch', True)
In [4]:
def simulate(n): wonWhenSwitched = 0 lostWhenSwitched = 0 wonWhenStayed = 0 lostWhenStayed = 0 for _ in range(n): movement, prize = run() if movement == 'switch': if prize == 1: wonWhenSwitched += 1 else: lostWhenSwitched += 1 elif movement == 'stay': if prize == 1: wonWhenStayed += 1 else: lostWhenStayed += 1 print(f'Switch and win: {round(wonWhenSwitched*100/(wonWhenSwitched+lostWhenSwitched), 3)} %') print(f'Switch and lose: {round(lostWhenSwitched*100/(wonWhenSwitched+lostWhenSwitched), 3)} %\n') print(f'Stay and win: {round(wonWhenStayed*100/(wonWhenStayed + lostWhenStayed), 3)} %') print(f'Stay and lose: {round(lostWhenStayed*100/(wonWhenStayed + lostWhenStayed), 3)} %')
In [5]:
simulate(1_000_000_000)
Switch and win: 66.669 % Switch and lose: 33.331 % Stay and win: 33.33 % Stay and lose: 66.67 %