Last active
September 27, 2023 21:02
-
-
Save Ranudar/81bbfd243a657428a1965db6b48a14c1 to your computer and use it in GitHub Desktop.
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
from random import choice, shuffle | |
class Monty_Hall: | |
"""This represents the initial puzzle setup with three doors.""" | |
def __init__(self): | |
self.doors_to_chose_from = ["goat_1", "goat_2", "car"] | |
shuffle(self.doors_to_chose_from) | |
def __call__(self, change=True): | |
"""Calling the instance plays once. If change=1 chose the changing strategy.""" | |
self.pick_initial_door() | |
self.show_goat() | |
if change: | |
self.change_to_other_door() | |
return self.player_is_winner() | |
def pick_initial_door(self): | |
self.picked_door = choice(self.doors_to_chose_from) | |
self.doors_to_chose_from.remove(self.picked_door) | |
def show_goat(self): | |
if self.picked_door == "goat_1": # if the player chose a goat... | |
self.doors_to_chose_from.remove("goat_2") # show the other goat and remove it from the options | |
elif self.picked_door == "goat_2": | |
self.doors_to_chose_from.remove("goat_1") | |
def change_to_other_door(self): | |
"""pick the remaining unopened door.""" | |
self.picked_door = self.doors_to_chose_from[0] | |
def player_is_winner(self): | |
if self.picked_door == "car": | |
return True | |
else: | |
return False | |
def run_simulation(num_of_simulations, change_strategy=True): | |
"""Use a list comprehension to create instances of Monty_Hall and call them""" | |
simulations = [Monty_Hall()(change_strategy) for i in range(num_of_simulations)] | |
return sum(simulations)/num_of_simulations | |
if __name__ == "__main__": | |
num_of_runs = 1000 | |
change_door_strategy = [True, False] | |
for change_strategy in change_door_strategy: | |
print(f"- After {num_of_runs} repetitions with {change_strategy=} we win in {run_simulation(num_of_runs, change_strategy)}% of runs.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment