simulate the monty hall problem in python

Here's one way to simulate the Monty Hall problem in Python:

main.py
import random

def simulate(num_trials):
    switch_wins = 0
    stay_wins = 0
    
    for i in range(num_trials):
        # There are 3 doors, and the prize is behind one of them
        doors = [0, 0, 0]
        prize_index = random.randint(0, 2)
        doors[prize_index] = 1
        
        # The player chooses a door at random
        choice_index = random.randint(0, 2)
        choice = doors[choice_index]
        
        # The host selects a door to reveal that does not contain the prize
        options = [i for i in range(3) if i != choice_index and doors[i] == 0]
        reveal_index = random.choice(options)
        
        # The player chooses whether to switch or stay with their original choice
        switch_options = [i for i in range(3) if i != choice_index and i != reveal_index]
        switch_index = random.choice(switch_options)
        switch_choice = doors[switch_index]
        
        # Check if the player wins if they switch or stay
        if choice == 1:
            stay_wins += 1
        elif switch_choice == 1:
            switch_wins += 1
    
    print("Switch wins: ", switch_wins)
    print("Stay wins: ", stay_wins)
    print("Switch win percentage: ", switch_wins / num_trials)
    print("Stay win percentage: ", stay_wins / num_trials)

# Example usage: simulate 10000 trials
simulate(10000)
1344 chars
39 lines

This code simulates the Monty Hall problem with a specified number of num_trials. Each trial follows the same steps as the classic problem: the player chooses a door, the host reveals one of the other doors, and the player chooses to switch or stay. The function keeps track of how many times the player wins if they switch or stay, and at the end of the simulation prints out the win percentages for each strategy.

gistlibby LogSnag