Skip to content

Instantly share code, notes, and snippets.

@samsonq
Created November 16, 2022 16:27
Show Gist options
  • Save samsonq/913629465736f01b8c1080d02b30b143 to your computer and use it in GitHub Desktop.
Save samsonq/913629465736f01b8c1080d02b30b143 to your computer and use it in GitHub Desktop.
Monty Hall Problem Simulation
import numpy as np
def monty_hall():
doors = np.array([1, 0, 0])
np.random.shuffle(doors)
initial_choice = np.random.randint(len(doors))
goat_door = 0
for i in range(len(doors)):
if i == initial_choice:
continue
elif doors[i] == 0:
goat_door = i
break
switch_choice = 3-(initial_choice+goat_door)
return doors[initial_choice]==1, doors[switch_choice]==1
def monte_carlo_simulation(n=10000):
no_switch_results = []
switch_results = []
for _ in range(n):
no_switch, switch = monty_hall()
no_switch_results.append(no_switch)
switch_results.append(switch)
return sum(no_switch_results)/n, sum(switch_results)/n
if __name__ == "__main__":
switch, no_switch = monte_carlo_simulation()
print("Probability of winning with switching: {}".format(switch))
print("Probability of winning with no switching: {}".format(no_switch))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment