Skip to content

Instantly share code, notes, and snippets.

@shon
Created August 30, 2019 17:27
Show Gist options
  • Save shon/02dcc31f6ca67f09446497aa5c6830ef to your computer and use it in GitHub Desktop.
Save shon/02dcc31f6ca67f09446497aa5c6830ef to your computer and use it in GitHub Desktop.
Monty Hall Problem Verification
import random
from dataclasses import dataclass
NO_OF_DOORS = 3
@dataclass
class Door:
no: int
prized: bool = False
selected: bool = False
def choose(self):
return self.prized
class Doors:
def __init__(self):
self.doors = [Door(no) for no in range(NO_OF_DOORS)]
prized_door = random.choice(self.doors)
prized_door.prized = True
self.selected = None
self.available = self.doors
def choose(self, door):
self.selected = door
self.selected.selected = True
self.available = [d for d in self.doors if d != self.selected]
def eliminiate(self):
elm_cadidates = [d for d in self.available if not (d.prized or d.selected)]
eliminiated = random.choice(elm_cadidates)
self.available = [d for d in self.doors if d != eliminiated]
def verdict(self):
return self.selected.prized
def play_stick():
doors = Doors()
choice = random.choice(doors.available)
doors.choose(choice)
doors.eliminiate()
doors.choose(choice)
return doors.verdict()
def play_switch():
doors = Doors()
choice = random.choice(doors.available)
doors.choose(choice)
doors.eliminiate()
choice = random.choice(doors.available)
doors.choose(choice)
return doors.verdict()
def main(n):
print(f'\niterations: {n}')
stick_wins = 0
switch_wins = 0
for i in range(n):
if play_stick():
stick_wins += 1
if play_switch():
switch_wins += 1
print(f'stick: {round(stick_wins*100/n, 1)}')
print(f'switch: {round(switch_wins*100/n, 1)}')
if __name__ == '__main__':
main(10)
main(100)
main(1000)
main(10000)
main(100000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment