Monty Hall Simulation — Python!

wu am i
Oct 31, 2020

The Monty Hall problem is a brain teaser, there are several ways to explain the solution but none would be so convincing as a simple simulation.

Here is the one in Python for “Always Switch”

import numpy as np
import random
#large sampling
sample = 1000000
#initialize doors and others
doors = ['car','goat','goat']
win = 0
lose = 0
for n in range(sample):
#shuffle every time
random.shuffle(doors)
# where is the car? zero index so add 1
c = doors.index('car')+1
# random select 1..3
i = random.randint(1,3)
#incease you want to know Monty opens? neither i or c
o = [v for v in [1,2,3]if v not in [i,c]]
#always switch, so if original selection is car
#then it's a lose
if(i == c):
lose += 1
else:
win +=1
##print the results of always switch##
print("Wins:{}, Losses:{}, Prob:{:.4f}".format(win, lose, win/(win+lose)))
[out] Wins:666698, Losses:333302, Prob:0.6667

That’s all folks!

PS: Image courtesy https://en.wikipedia.org/wiki/Monty_Hall_problem

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

wu am i
wu am i

Written by wu am i

truth serum - pythonist, perpetual learner, ai/ml enthusiast, hope to build a personal robotic assistant (pra?) to take care me in my old age!

No responses yet

Write a response