Our first task is to randomly choose a door for the prize. I’m going to use a random integer between 0 and 2. That’s three numbers: 0, 1, 2. (Like many programming languages, Python starts counting from zero.)
After that, I need to randomly pick a number to represent the door the contestant chooses. Again that’s 0, 1, or 2. If these two numbers match, the player wins. I can repeat this as many times as I like and count the number of wins divided by the number of tries. That’s it. Here’s the code.
In the embed below, you can click between the pencil icon to see the code and the arrow icon to view the result.
This is live code, so you can change the number of trials and then run it again. (It’s currently set at N = 1,000 in line 4.) If N is quite small, like 10 or 20 trials, then you are going to see some fluctuations in the win percentage. With large numbers, like 1,000, things start to be better behaved. You should be getting a win percentage close to 33, which is about one third, or a one in three chance of winning.
I should add that if the contestant does not switch doors after Monty shows them what’s behind one of the losing doors, nothing changes. They already picked their door, so if they stick with it, their odds of winning won’t improve. They will remain one in three.
The Door-Switching Option
I’ll be honest: This option is a bit more complicated to model. Not only do I need to pick the door with the prize and the choice for the contestant, but I need to pick a losing door for Monty to open and then switch the choice of the player.
Before you look at the code below, I want to remind you that I’m a physicist and not a programmer, so it can be considered a little sloppy. Maybe there are better ways to do it, but since I built it, I understand it. It’s my code. It’s not some black box with a button to push that gives an answer. What I mean is: Your program doesn’t have to be perfect. Don’t let that stop you from coding.
You can really only see the differences between switching and not switching with larger numbers. (Once again, toggle between the pencil and the arrow to see the code and the results.) This time, if we run 1,000 trials in which the player switches doors after Monty’s reveal, they win about two thirds of the time, which is the theoretical solution to this problem.
If you think this seems strange, then I agree with you. Here’s the basic explanation: With three doors you have a 1 in 3 probability of winning. When Monty opens one of the doors, he’s basically giving you an extra pick—if you switch—so you now have 2 in 3 chances of winning.