Monty Hall Problem with Python

#python

The Monty Hall problem is a classic brain teaser that’s quite famous. I remember trying to understand the puzzle by simulating it ages ago. I can’t remember what language I used back then, or even if I succeeded. Today I found this Numberphile video about it and was tempted to try again in Python.

The problem is based on an American game show where the contestant could win a car. The car was hidden behind one of three doors. The contestant first selected a door. The game show host (Monty Hall) then opened one of the other two doors, revealing no car behind it. The contestant now got the chance to chose the other unopened door instead, if they so wanted.

The problem to solve is this: is it advantageous to switch doors?

"""
Monty Hall problem.
"""

from random import randrange
from random import choice

def play(stay_strategy):
    """
    Simulate a contestant trying to win the car using the provided strategy
    """
    doors = {1, 2, 3}
    price = randrange(1, 4)
    chosen = randrange(1, 4)
    monty = choice(list(doors - {chosen, price}))
    chosen = chosen if stay_strategy else int(*doors - {chosen, monty})
    return chosen == price

N = 10000

print('Stay:', sum([play(stay_strategy=True) for i in range(N)]) / N)
print('Swap:', sum([play(stay_strategy=False) for i in range(N)]) / N)

Example results:

Stay: 0.3362
Swap: 0.6661