Skip to content

Instantly share code, notes, and snippets.

@hyonschu
Created May 9, 2014 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyonschu/c3ccd51c17aec9fb9ae1 to your computer and use it in GitHub Desktop.
Save hyonschu/c3ccd51c17aec9fb9ae1 to your computer and use it in GitHub Desktop.
class montymc(object):
"""
### VARIABLES ###
samples = how many trials to run
simulations = number of simulations of X samples
doors = number of doors for the game (default: 3)
switch dictates what the user does after monty opens the door:
switch = 0, no switching
switch = 1, always switch
switch = 2, random
### METHODS AND INSTANCES ###
.wins returns a list of wins for every simulation
.totals returns a list of total trials per simulation
.percentage returns a list of wins/totals per simulation
.results() prints all wins, totals, percentage
.average() returns the average of all win percentages
"""
def __init__(self, samples=100, simulations=5,doors=3, switch=1):
# print "Ready to go! Run simulations using"
# print ".simulation(samples, simulations, doors, switch)"
self.samples = samples
self.simulations = simulations
self.doors = doors
self.switch = switch
self.simuran = 0
self.simulation(samples, simulations, doors, switch)
def simulation(self, samples, simulations, doors, switch):
doors = self.doors
simulations = self.simulations
switch = self.switch
if doors < 3: # too few doors!
return "Monty Hall demands at least 3 doors!"
if switch > 2:
return "error: switch=0: no switching; 1: always switch; 2: random switch"
simuresults = [] #initiate empty list to keep
for i in range(simulations):
wins = 0
total = 0
for i in range(self.samples):
alldoors = [ i for i in range(doors) ]
car = random.randint(0,doors-1)
guess = random.randint(0,doors-1)
montydoor = random.randint(0,doors-1)
while montydoor == car or montydoor == guess:
montydoor = random.randint(0,doors-1)
if montydoor > doors:
return "something went wrong - monty can't open this door"
alldoors.pop(montydoor)
newguess = random.randint(0,doors-1)
if self.switch == 0:
newguess == guess
elif self.switch == 1:
while newguess==guess or newguess==montydoor:
newguess = random.randint(0,doors-1)
elif self.switch == 2:
newguess = alldoors[random.randint(0,len(alldoors)-1)]
if newguess == car:
wins += 1
total += 1
simuresults.append([wins,total,wins*1.00/total])
self.wins = [i[0] for i in simuresults]
self.total = [i[1] for i in simuresults]
self.percentage = [i[2] for i in simuresults]
self.simuran=1
def results(self):
if self.simuran==0:
return "please run simulation() first"
else:
print self.wins
print self.total
print self.percentage
def average(self):
return np.mean(self.percentage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment