Skip to content

Instantly share code, notes, and snippets.

@jpark9013
Last active July 1, 2020 03:35
Show Gist options
  • Save jpark9013/05cafed07399719c93f6af961ed90b8f to your computer and use it in GitHub Desktop.
Save jpark9013/05cafed07399719c93f6af961ed90b8f to your computer and use it in GitHub Desktop.
Run monty hall on python
# Monty hall problem
import random
def run():
stay = 0
dif = 0
for i in range(100000):
# doing different door
car = random.randint(0, 2)
choice = random.randint(0, 2)
# Using set comphrehension because it's more efficient
lst = [i for i in {0, 1, 2} if i not in {car, choice}]
# Random choice if car and original choice were the same, then lst is length 2, otherwise it will return the original element anyway
revealed = random.choice(lst)
# Switch to the alternative choice, which will not be the original choice or the revealed door
lst = [i for i in {0, 1, 2} if i not in {revealed, choice}]
# Checking if the swapped choice or original choice were the same as the car
if lst[0] == car:
dif += 1
elif choice == car:
stay += 1
print(f"{stay/1000}%")
print(f"{dif/1000}%")
# Running the function, faster to wrap the program in a function so that there are no global vars
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment