Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# bhelx/montyhall.py

Last active Aug 29, 2015
Simulation to prove answer to monty hall problem
 import numpy as np # returns a numpy array of n doors with the prize range 0-2 def simulate_prizedoors(n): return np.random.random_integers(0, 2, size=n) # returns a numpy array of n contestant guesses with range 0-2 def simulate_guesses(n): return np.random.random_integers(0, 2, size=n) # returns a numpy array of doors the host would show with the goat def goatdoors(guesses, prizedoors): return [np.setdiff1d([0, 1, 2], [prizedoors[i], guesses[i]])[0] for i in range(len(prizedoors))] # switches guess based on the goat door shown def switch_guess(guesses, goatdoors): return [np.setdiff1d([0, 1, 2], [guesses[i], goatdoors[i]])[0] for i in range(len(guesses))] # returns percentages of wins def win_percentage(guesses, prizedoors): count = 0 for i in range(len(guesses)): if guesses[i] == prizedoors[i]: count += 1 return 100.0 * count / float(len(guesses)) N = 10000 prizedoors = simulate_prizedoors(N) guesses = simulate_guesses(N) print "Wins without switching %f" % win_percentage(guesses, prizedoors) prizedoors = simulate_prizedoors(N) guesses = simulate_guesses(N) goatdoors = goatdoors(guesses, prizedoors) print "Wins with switching: %f" % win_percentage(switch_guess(guesses, goatdoors), prizedoors)
 Wins without switching 31.880000 Wins with switching: 67.630000
to join this conversation on GitHub. Already have an account? Sign in to comment