Skip to content

Instantly share code, notes, and snippets.

@snitzr

snitzr/monty_hall.py

Last active Apr 1, 2020
Embed
What would you like to do?
Monty Hall problem outcome simulator
import random
# probability calculator
def monty():
runs = 5000
true_switch_win_counter = 0
false_switch_win_counter = 0
true_switch_counter_total = 0
false_switch_counter_total = 0
for i in range(runs):
print('____________________\nBegin for loop #{}\n'.format(i+1))
doors = ['1', '2', '3']
initial_pick = random.choice(doors)
winning_door = random.choice(doors)
print('Doors: {}'.format(doors))
print('Initial pick: {}'.format(initial_pick))
print('Winning door: {}\n'.format(winning_door))
# switcher
if i % 2:
true_switch_counter_total += 1
print('Switch True')
second_pick = 0
if winning_door == initial_pick:
# guaranteed loss
print('Winning door: {} == Intial pick: {}'
.format(winning_door, initial_pick))
print('Lose. Switched from correct initial pick')
else:
# guaranteed win
print('Winning door: {} != Intial pick: {}'
.format(winning_door, initial_pick))
print('Win. Switched from incorect initial pick.')
true_switch_win_counter += 1
else:
false_switch_counter_total += 1
print('Switch False')
if initial_pick == winning_door:
print('Initial pick: {} == Winning door: {}'
.format(initial_pick, winning_door))
print('Win. Not switched.')
false_switch_win_counter += 1
else:
print('Initial pick: {} != Winning door: {}'
.format(initial_pick, winning_door))
print('Lose. Not switched.')
print('\nEnd for loop #{}\n--------------------\n'.format(i+1))
print('Wins with switch:\t{:.3f}%'
.format(true_switch_win_counter / true_switch_counter_total * 100))
print('Wins without switch:\t{:.3f}%'
.format(false_switch_win_counter / false_switch_counter_total * 100))
print('true_switch_win_counter: {} / true_switch_counter_total: {}'
.format(true_switch_win_counter, true_switch_counter_total))
print('false_switch_win_counter: {} / false_switch_counter_total: {}'
.format(false_switch_win_counter, false_switch_counter_total))
if __name__ == "__main__":
# run function on startup
monty()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment