Last active
July 18, 2018 16:58
-
-
Save shayneoneill/320398881e8d966e6347fd24a5404c34 to your computer and use it in GitHub Desktop.
Monte-Carlo Monty Hall Million Goat Simulator (Remember, the excluded goat gets to go the next round!)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Monte-Carlo Monty Hall Million Goat Simulator | |
# Featuring some pretty damn lazy math | |
# Shayne | |
# | |
from random import randint | |
from functools import partial | |
rand3 = partial(randint,0,2) | |
class GoatSimulator(object): | |
def setup(self): | |
self.doors = ['goat','goat','goat'] | |
self.doors[rand3()] = 'car' | |
def select(self,exclude=4): | |
selected = exclude | |
while selected == exclude: | |
selected = rand3() | |
return [selected,self.doors[selected]] | |
def spare_goat(self,selection): | |
for i in range(0,len(self.doors)): | |
if i == selection or self.doors[i] == 'car': | |
continue | |
return [i,self.doors[i]] | |
def swap_vote(self,selection,excluded): | |
for i in range(0,len(self.doors)): | |
if i in [selection,excluded]: | |
continue | |
return [i,self.doors[i]] | |
def run(self,run_number=0,show=True): | |
self.setup() | |
selection1 = self.select() | |
exclude = self.spare_goat(selection1[0]) | |
selection2 = self.swap_vote(selection1[0],exclude[0]) | |
if show: | |
print ("Run number {} Initial doors:{}".format(run_number,self.doors)) | |
print ("Selected : {}".format(selection1)) | |
print ("Excluding: {}",format(exclude)) | |
print ("Selected2: {}",format(selection2)) | |
return[self.doors,selection1,selection2,exclude] | |
class GoatRunner(object): | |
def avg (self,count,guesses): | |
return (float(guesses) / float(count)) * 100.0 | |
def run(self,size=100000): | |
arr = [] | |
g = GoatSimulator() | |
runs = 0 | |
first_guess = 0 | |
second_guess = 0 | |
for i in range(0,size): | |
x = g.run(i,False) | |
arr.append(x) | |
if x[1][1] == 'car': | |
first_guess += 1 | |
if x[2][1] == 'car': | |
second_guess += 1 | |
runs += 1 | |
print ("Runs: {} First Guess: {} Second Guess: {}".format(runs,self.avg(runs,first_guess),self.avg(runs,second_guess))) | |
if __name__ == '__main__': | |
g = GoatRunner() | |
g.run(size=1000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(spaceserver) Shaynes-MacBook-Pro:~ shayneoneill$ python goat.py
Runs: 1000000 First Guess: 33.3107 Second Guess: 66.6893