Eli R - 1 year ago 48

Python Question

I have made a Python script to test the Monty Hall Problem

My issue is that the code seems to output 30% wins and 60% losses when it should be doing the opposite.

`from random import randint`

wins = 0

losses = 0

for i in range(1000):

correctDoor = randint(1, 3)

guessDoor = randint(1, 3)

while True:

newGuessDoor = randint(1, 3)

if newGuessDoor != guessDoor:

break

elif newGuessDoor == guessDoor:

pass

if newGuessDoor == correctDoor:

wins = wins+1

else:

losses = losses+1

print('Wins = ' + str(wins) + '\nLosses = ' + str(losses) + '')

I feel like I'm missing something blatantly obvious.

Any help will be appreciated.

Answer Source

This isn't actually implementing the Monty Hall problem correctly. When the initial guess is not correct, the other incorrect door is revealed before being given the offer to switch, and so it's a deterministic option. When the initial guess is correct, one of the other incorrect doors is revealed at random.

In your implementation, you're not being given any extra information after the initial guess -- you're just picking a 2nd door completely at random that isn't the same as your first door.

Here's an example of how you could implement the right method:

```
In [168]: from random import randint, choice
...: wins = 0
...: losses = 0
...: for i in range(1000):
...: correctDoor = randint(1, 3)
...: guessDoor = randint(1, 3)
...: if guessDoor != correctDoor:
...: newGuessDoor = correctDoor
...: else:
...: newGuessDoor = choice([i for i in [1,2,3] if i != guessDoor])
...: if newGuessDoor == correctDoor:
...: wins = wins+1
...: else:
...: losses = losses+1
...: print('Wins = ' + str(wins) + '\nLosses = ' + str(losses) + '')
...:
Wins = 653
Losses = 347
```