(a) Write a program that simulates playing this game 10000 times and calculates what per�centage of the time you would win if you switch and what percentage of the time you would win by not switching.



import random

def monty_hall_simulation(num_simulations):
stay_wins = 0
switch_wins = 0

for _ in range(num_simulations):
# Randomly place the prize behind one of the three doors
doors = ["goat", "goat", "prize"]
random.shuffle(doors)

# Contestant makes an initial choice
initial_choice = random.randint(0, 2)

# Monty opens one of the other doors with a goat
monty_choices = [i for i in range(3) if i != initial_choice and doors[i] == "goat"]
monty_open = random.choice(monty_choices)

# Contestant's options after Monty's revelation
remaining_choices = [i for i in range(3) if i != initial_choice and i != monty_open]

# Determine outcomes for staying and switching
if doors[initial_choice] == "prize":
stay_wins += 1
else:
switch_wins += 1

stay_percentage = (stay_wins / num_simulations) * 100
switch_percentage = (switch_wins / num_simulations) * 100

print(f"Simulations: {num_simulations}")
print(f"Percentage of wins by staying: {stay_percentage:.2f}%")
print(f"Percentage of wins by switching: {switch_percentage:.2f}%")

if __name__ == "__main__":
num_simulations = 10000
monty_hall_simulation(num_simulations)



(b) Try the above but with four doors instead of three. There is still only one prize, and Monty still opens up one door and then gives you the opportunity to switch.



import random

def monty_hall_simulation_four_doors(num_simulations):
stay_wins = 0
switch_wins = 0

for _ in range(num_simulations):
# Randomly place the prize behind one of the four doors
doors = ["goat", "goat", "goat", "prize"]
random.shuffle(doors)

# Contestant makes an initial choice
initial_choice = random.randint(0, 3)

# Monty opens one of the other doors with a goat
monty_choices = [i for i in range(4) if i != initial_choice and doors[i] == "goat"]
monty_open = random.choice(monty_choices)

# Contestant's options after Monty's revelation
remaining_choices = [i for i in range(4) if i != initial_choice and i != monty_open]

# Determine outcomes for staying and switching
if doors[initial_choice] == "prize":
stay_wins += 1
else:
switch_wins += 1

stay_percentage = (stay_wins / num_simulations) * 100
switch_percentage = (switch_wins / num_simulations) * 100

print(f"Simulations: {num_simulations}")
print(f"Percentage of wins by staying: {stay_percentage:.2f}%")
print(f"Percentage of wins by switching: {switch_percentage:.2f}%")

if __name__ == "__main__":
num_simulations = 10000
monty_hall_simulation_four_doors(num_simulations)



These programs simulate the Monty Hall problem for 10,000 iterations and calculate the percentage of wins when staying and when switching doors, for both three and four doors scenarios.