I wrote a function to simulate the Monty Hall problem (

http://en.wikipedia.org/wiki/Monty_Hall_problem). When I run it I get a 1/3 chance of winning the car when the contestant doesn't switch doors, which is right, but I also get a 5/9 chance of winning when the contestant does switch doors. From what I understand about the problem, the contestant should have a 2/3 chance of winning if they do switch doors, so I'm wondering what is wrong with the function. I'm pretty new to programming, so it may be something kind of obvious that I'm missing.

- Code: Select all
`def monty_hall(num_trials):`

''' (int) -> [int, float, int, float]

Return a list where the first item is the number of times the contestant

wins the car when they choose to switch doors, the second item is the

fraction of times the contestant wins when they switched, the third item

is the number of times the contestant wins the car when they choose to

not switch doors, and the fourth item is the fraction of times they win

when they didn't switch. In this version of the problem (which is the

traditional version), the host knows which door the car is behind, and

only reveals a door that does not have the car behind it.

'''

result = [0, 0, 0, 0]

contestant_choice = 0

host_reveal = 0

import random

for trial in range(num_trials):

car = random.randint(1,3)

contestant_choice = random.randint(1,3)

host_reveal = random.randint(1,3)

# To make sure that the door the host reveals isn't the same as the one the

# contestant chose, and isn't the one with the car behind it.

while (host_reveal == contestant_choice or host_reveal == car):

host_reveal = random.randint(1,3)

# What happens when the contestant does not switch doors after the host reveal.

if contestant_choice == car:

result[2] = result[2] + 1

# What happens when the contestant switches doors after the host reveal.

if contestant_choice == 1 and host_reveal == 2:

contestant_choice = 3

elif contestant_choice == 1 and host_reveal == 3:

contestant_choice = 2

elif contestant_choice == 2 and host_reveal == 1:

contestant_choice == 3

elif contestant_choice == 2 and host_reveal == 3:

contestant_choice = 1

elif contestant_choice == 3 and host_reveal == 1:

contestant_choice = 2

elif contestant_choice == 3 and host_reveal == 2:

contestant_choice == 1

if contestant_choice == car:

result[0] = result[0] + 1

result[1] = float(result[0]) / float(num_trials)

result[3] = float(result[2]) / float(num_trials)

return result