|
| 1 | +""" |
| 2 | +Monty Hall |
| 3 | +Code the classic Monty Hall problem! |
| 4 | +
|
| 5 | +The following is a description of the Monty Hall Problem: |
| 6 | + There are three closed doors, 2 have goats behind them, |
| 7 | + only one has a car behind it. |
| 8 | + You don't know which door has what. |
| 9 | + The goal is to pick the door that has the car behind it. |
| 10 | + After you make a choice, Monty (the host) opens a door |
| 11 | + that you did not choose, revealing a goat. |
| 12 | + You are then asked whether you want to |
| 13 | + change your choice to the other door. |
| 14 | + The door you chose is more likely to have a car |
| 15 | + if you switch to the other door, apparently! |
| 16 | +
|
| 17 | +More step-by-step instructions (pseudocode) are commented below. |
| 18 | +
|
| 19 | +Read more about the Monty Hall Problem here: |
| 20 | +https://betterexplained.com/articles/understanding-the-monty-hall-problem/ |
| 21 | +""" |
| 22 | + |
| 23 | +# Make a list that represents the three closed doors, |
| 24 | +# 'G' for the doors that have a goat, 'C' for the door that has a car. |
| 25 | +import random |
| 26 | +doors = ['G', 'G', 'C'] |
| 27 | + |
| 28 | +# Make the Monty Hall game repeat 6 times. |
| 29 | +for i in range(6): |
| 30 | + # Randomize the doors |
| 31 | + random.shuffle(doors) |
| 32 | + |
| 33 | + # reset the doors left |
| 34 | + doors_left = [1, 2, 3] |
| 35 | + |
| 36 | + # The user enters their 1st choice |
| 37 | + print("A new Monty Hall game has begun!") |
| 38 | + choice = int(input("Choose from doors 1, 2, or 3...\n> ")) |
| 39 | + doors_left.remove(choice) |
| 40 | + |
| 41 | + # A door that has a goat is revealed, cannot be the one user chose |
| 42 | + # makes a duplicate list to avoid messing up the original |
| 43 | + reveal_doors = doors.copy() |
| 44 | + |
| 45 | + # removes user's choice so that it won't be opened, |
| 46 | + # but keeps in the element to not mess up the indices |
| 47 | + reveal_doors[choice - 1] = '-' |
| 48 | + goat_door = reveal_doors.index('G') + 1 |
| 49 | + doors_left.remove(goat_door) |
| 50 | + print("Monty opens door", goat_door, "to reveal a goat!") |
| 51 | + |
| 52 | + # The user is prompted to choose again |
| 53 | + print("With this new information, do you want to switch doors?") |
| 54 | + print("Your first choice was Door", choice) |
| 55 | + print("If you switch, you will be opening Door", doors_left[0]) |
| 56 | + print("Enter 'y' to switch, or 'n' to keep your first choice.") |
| 57 | + switch = input("> ") |
| 58 | + |
| 59 | + if switch == 'y': |
| 60 | + choice = doors_left[0] |
| 61 | + |
| 62 | + # The prize behind the user's ultimate choice is revealed! |
| 63 | + if doors[choice - 1] == 'C': |
| 64 | + print("You got... a car! Congratulations!") |
| 65 | + else: |
| 66 | + print("You got... a goat! Better luck next time!") |
| 67 | + |
| 68 | + print() |
0 commit comments