Created
September 6, 2017 00:54
-
-
Save itsaandy/f1cc55a569e3232631ac39cbfd2b4f9e to your computer and use it in GitHub Desktop.
Monty Hall Problem Simulation
This file contains 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
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