Skip to content

Instantly share code, notes, and snippets.

@adusak
Created June 2, 2015 17:54
Show Gist options
  • Save adusak/08a4d2c15c532da6b6ea to your computer and use it in GitHub Desktop.
Save adusak/08a4d2c15c532da6b6ea to your computer and use it in GitHub Desktop.
Monty Hall Problem simulator
import random
def monty_hall(door_selection=None, _choice=None):
doors = ["goat" for _ in range(3)]
car_index = random.randint(0, 2)
doors[car_index] = "CAR"
door_number = door_selection
if door_number is None:
door_number = int(input("Vyberte dvere c. 1, 2 nebo 3\n")) - 1
l = [0, 1, 2]
l.remove(door_number)
if door_number == car_index:
opened_index = random.choice(l)
if door_selection is None:
print("Otevreny dvere c", str(opened_index + 1))
else:
l.remove(car_index)
opened_index = l[0]
if door_selection is None:
print("Otevreny dvere c", str(opened_index + 1))
if door_selection is None:
print("chcete zmenit volbu dveri?")
choice = _choice
if choice is None:
choice = input("Ano (a), Ne (n), Nahoda (r)\n")
if choice == "r":
choice = random.choice(["a", "n"])
l = [0, 1, 2]
l.remove(door_number)
l.remove(opened_index)
if choice == "n":
if door_selection is None:
print(doors[door_number])
if doors[door_number] == "CAR":
return True
else:
return False
elif choice == "a":
if door_selection is None:
print(doors[l[0]])
if doors[l[0]] == "CAR":
return True
else:
return False
count_yes = 0
count_no = 0
count_rand = 0
for i in range(10000):
res = monty_hall(random.randint(0, 2), "a")
if res:
count_yes += 1
res = monty_hall(random.randint(0, 2), "n")
if res:
count_no += 1
res = monty_hall(random.randint(0, 2), "r")
if res:
count_rand += 1
print("Wins, when decision changed", (count_yes / 10000) * 100, "%")
print("Wins, when decision stayed", (count_no / 10000) * 100, "%")
print("Wins, when decision was random", (count_rand / 10000) * 100, "%")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment