Monty Hall Problem in Python

The Monty Hall problem is a classic probability puzzle named after the host of the game show “Let’s Make a Deal.” In the problem, there are three doors, behind one of which is a prize, and behind the other two are goats. The contestant chooses a door, and then the host (Monty Hall) opens one of the other two doors to reveal a goat. The contestant is then given the option to switch their choice to the remaining door or stick with their original choice. The question is: should the contestant switch their choice or not?

At first glance, it may seem like the odds of winning are 50-50, but in fact, the optimal strategy is to always switch. To understand why, we can use Python to simulate the game and see what happens.

import random
def monty_hall(switch):
    # place the prize behind one of the doors
    doors = ['goat', 'goat', 'prize']
    random.shuffle(doors)
    
    # contestant chooses a door
    choice = random.choice([0, 1, 2])
    
    # host opens a door with a goat
    shown = random.choice([i for i in range(3) if i != choice and doors[i] == 'goat'])
    
    if switch:
        # contestant switches to the other unopened door
        choice = [i for i in range(3) if i != choice and i != shown][0]
    
    # determine if the contestant wins
    return doors[choice] == 'prize'

# run the simulation for both switching and not switching
num_trials = 100000
wins_with_switch = sum([monty_hall(True) for i in range(num_trials)])
wins_without_switch = sum([monty_hall(False) for i in range(num_trials)])

# print the results
print(f"With switching: {wins_with_switch} wins out of {num_trials} trials")
print(f"Without switching: {wins_without_switch} wins out of {num_trials} trials")

In this code, the monty_hall function simulates the game for one round, taking a boolean switch parameter that indicates whether the contestant will switch their choice or not. The function first places the prize behind one of the doors, then randomly chooses the contestant’s initial choice and the door to be shown by the host. If the contestant switches, the function chooses the remaining unopened door. Finally, the function determines whether the contestant wins or not.

The for loops at the end run the simulation for a large number of trials (in this case, 100,000) and count the number of wins with and without switching. The results show that switching is indeed the better strategy: the contestant wins around 67% of the time when they switch, but only around 33% of the time when they don’t.

In conclusion, the Monty Hall problem is a classic example of how probability can sometimes be counterintuitive. By using Python to simulate the game and run many trials, we can see that the optimal strategy is to always switch. This problem serves as a reminder that probability theory can sometimes produce surprising results, and that computational tools like Python can be powerful aids in understanding them.