Skip to content

Instantly share code, notes, and snippets.

@itsaandy
Created September 6, 2017 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsaandy/f1cc55a569e3232631ac39cbfd2b4f9e to your computer and use it in GitHub Desktop.
Save itsaandy/f1cc55a569e3232631ac39cbfd2b4f9e to your computer and use it in GitHub Desktop.
Monty Hall Problem Simulation
import random
import sys
def monty_hall(choice, switch):
'''
@param
:choice: - int between 1 and 3.
:switch: - boolean. Switches choice if true.
'''
wins, losses = 0, 0
# Random suffle of the doors.
doors = ["goat", "goat", "car"]
random.shuffle(doors)
# Show one of the goats.
goat_door = 0
for i in range(3):
if doors[i-1] == "goat" and choice != i:
goat_door = i
# Switch the option if the "switch" is passed as True
if(switch):
n = {1, 2, 3} - {choice, goat_door}
choice = n.pop()
# Final reveal
if doors[choice-1] == "goat":
return False
else:
return True
ITERATIONS = 10000
if __name__ == "__main__":
if len(sys.argv) == 2:
ITERATIONS = int(sys.argv[1])
no_switch_wins = 0
no_switch_losses = 0
switch_wins = 0
switch_losses = 0
# Play the Monty Hall game $ITERATIONS times.
for i in range(ITERATIONS):
choice = random.randrange(3)
if(monty_hall(choice, True)):
switch_wins += 1
else:
switch_losses += 1
if(monty_hall(choice, False)):
no_switch_wins += 1
else:
no_switch_losses += 1
# Output
print("\nNo switch data:")
print(" - WINS : " + str(no_switch_wins))
print(" - LOSSES : " + str(no_switch_losses))
print("Switch data:")
print(" - WINS : " + str(switch_wins))
print(" - LOSSES : " + str(switch_losses))
print("Total games played : " + str(ITERATIONS))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment