Skip to content

Instantly share code, notes, and snippets.

@Joker-vD
Created July 28, 2020 18:32
Show Gist options
  • Save Joker-vD/5b1d5a75e31eaf5694fb6cf2e8077337 to your computer and use it in GitHub Desktop.
Save Joker-vD/5b1d5a75e31eaf5694fb6cf2e8077337 to your computer and use it in GitHub Desktop.
Monty Hall simulation
import random
show_games = False
all_doors = [1, 2, 3]
def show(*args, **kwargs):
if show_games:
print(*args, **kwargs)
def player_chose_first_time():
result = random.choice(all_doors)
show("Player choses", result)
return result
def host_chose_door_to_open(player_door, winning_door):
result = random.choice([d for d in all_doors if d != player_door and d != winning_door])
show("Host opens", result)
return result
def player_chose_second_time(player_first_door, other_door):
result = other_door
show("Player choses", result)
return result
def one_game():
winning_door = random.choice(all_doors)
show("New game, winning door is ", winning_door)
player_first_door = player_chose_first_time()
host_open_door = host_chose_door_to_open(player_first_door, winning_door)
if host_open_door == winning_door:
# can't happen when the host opens doors non-randomly
return False
other_door = [d for d in all_doors if d not in (player_first_door, host_open_door)][0]
show("Other remaining door is", other_door)
player_second_door = player_chose_second_time(player_first_door, other_door)
if player_second_door == winning_door:
show("Player wins!")
show()
return True
else:
show("Player loses...")
show()
return False
total_games = 10000
player_wins = 0
for i in range(total_games):
if one_game():
player_wins += 1
print("Player won", player_wins, "times out of", total_games, "(" + str(100.0 * (player_wins / total_games)) + "%)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment