Skip to content

Instantly share code, notes, and snippets.

@luvies
Created April 24, 2018 19:35
Show Gist options
  • Save luvies/47dbb32f1670732f892d72c3a4a4aa71 to your computer and use it in GitHub Desktop.
Save luvies/47dbb32f1670732f892d72c3a4a4aa71 to your computer and use it in GitHub Desktop.
Python version of the Monty Hall problem
#! /usr/bin/env python3
from random import randint, shuffle
TIMES = 10_000_000
def get_dict():
return {
"wins": 0,
"losses": 0
}
def process_result(choice, results, doors):
if doors[choice] == 1:
results["wins"] += 1
else:
results["losses"] += 1
def display_result(results, name):
print(name, "choice:")
print("\twins:", results["wins"])
print("\tlosses:", results["losses"])
print("\twin ratio:",
float(results["wins"]) / float(results["wins"] + results["losses"]))
def monty_hall():
first = get_dict()
second = get_dict()
for i in range(TIMES):
doors = [1, 0, 0]
shuffle(doors)
choice = randint(0, len(doors) - 1)
preopen = None
for i in range(len(doors)):
if doors[i] == 0 and i != choice:
preopen = i
break
assert preopen != choice
newchoice = None
for i in range(len(doors)):
if i != choice and i != preopen:
newchoice = i
break
assert newchoice != choice
assert newchoice != preopen
process_result(choice, first, doors)
process_result(newchoice, second, doors)
return (first, second)
if __name__ == "__main__":
results = monty_hall()
display_result(results[0], "first")
display_result(results[1], "second")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment