Search code examples
pythonsimulate

Monty 4doors python


I am working on a program to find the probability of having 4 doors in the Monty Hall problem, but the probability of changing the selection is not printed.

import random

door = ['a', 'b', 'c', 'd']
nc = 0 # When not changed
c = 0  # When changed

tr = 100 #Total number of iterations
for a in range(tr):
    car = random.randint(0, 3) #Inquiry number with car behind

    pc = random.randint(0, 3) #Inquiry number chosen by the participant

    ed = [] #Empty door

for i in range(4):
    if i != pc and i != car:
        ed.append(door[i])


com = random.sample(ed, 2)

if pc == car:
    nc += 1


def list_remover(the_list, val):
    while val in the_list:
        the_list.remove(val)

list_remover(ed, com)


if not ed:
    c += 1

print((nc / tr) * 100, "%")
print((c / tr) * 100, "%")

Solution

  • 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: