Monty 4doors python

The originally posted code is unclear (could be issue with indentation and I don’t follow code logic).

However, a Monty Hall simulation for any number of doors is as follows.

Code

from random import choice

# Number of doors
N_doors = int(input("How many doors (>= 3? "))

wins_change = 0                    # number of wins when we change doors
wins_no_change = 0                 # number of wins without changing doors
doors = list(range(1, N_doors+1))  # doors as list [1, 2, ... N_doors]
N_Trials = 10000                   # number of times to run simulation
for K in range(1, N_Trials): 
    # Host randomly chooses a door for answer
    host_pick = choice(doors) 
    
    # Player randomly chooses a door for their answer
    player_pick = choice(doors)
    
    # Host picks a door to show
    # that's not host_pick or player_pick
    # i.e. door won't be host_pick or player_pick
    show = choice([i for i in doors if i != host_pick and i != player_pick])
    
    # Update win count if player doesn't change selection now that a door is shown
    if host_pick == player_pick:
      wins_no_change += 1

    # Player changes selection 
    # i.e. picks door that's not shown and wasn't their original pick
    player_pick = choice([i for i in doors if i != show and i != player_pick])

    # Player wins if player_pick equals host_pick
    if player_pick == host_pick:
      wins_change += 1
    
# show results
print(f'Probablity winning not changing selection {wins_no_change/N_Trials:.2%}')
print(f'Probablity winning after changing selection {wins_change/N_Trials:.2%}')

Tests

Test 3 doors

How many doors (assume >= 3)? 3
Probablity winning not changing selection 33.29%
Probablity winning after changing selection 66.70%

Test 4 doors

How many doors? 4
Probablity winning not changing selection 25.73%
Probablity winning after changing selection 36.90%

Note:

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top