Skip to content

Instantly share code, notes, and snippets.

@57op
Created January 21, 2020 17:00
Show Gist options
  • Save 57op/fcf520ebd9a41e795456cf2eead783d6 to your computer and use it in GitHub Desktop.
Save 57op/fcf520ebd9a41e795456cf2eead783d6 to your computer and use it in GitHub Desktop.
Clear once and for all Monty Hall problem (though I might forget again)
from random import choice, randrange, sample
class MontyHall:
def __init__(self) -> None:
self.doors = sample(['car', 'goat', 'goat'], 3) # without replacement
def play(self, switch: bool) -> bool:
# find car door index
car_door = self.doors.index('car')
# you pick a door
your_door = randrange(0, 3)
# monthy opens a door
# the door cannot be the car door
# the door cannot be the player door
monty_door = choice([i for i in range(3) if i not in (your_door, car_door)])
# wanna change `your_door` with `(self.doors - your_door - monty_door)`?
if switch:
your_door = [i for i in range(3) if i not in (your_door, monty_door)][0]
return your_door == car_door
def main() -> None:
if_switch = []
if_not_switch = []
for _ in range(50000):
m = MontyHall()
if_not_switch.append(m.play(False))
if_switch.append(m.play(True))
print(if_switch.count(True) / len(if_switch))
print(if_not_switch.count(True) / len(if_not_switch))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment