Skip to content

Instantly share code, notes, and snippets.

@MarkTraceur
Created August 26, 2011 01:13
Show Gist options
  • Save MarkTraceur/1172453 to your computer and use it in GitHub Desktop.
Save MarkTraceur/1172453 to your computer and use it in GitHub Desktop.
Monty Hall Problem -- Statistical Analysis
This utility is meant for educational purposes. Please, on the honor system, don't use it as your own homework!
Otherwise, it is under this license: http://sam.zoy.org/wtfpl
Strategy 1, which is "stay every time" predictably won 33.33% of the time.
Strategy 2, "switch every time" won 66.67% of the time.
Strategy 3, "switch 33% of the time randomly" won 44.44% of the time.
If you can come up with a strategy that, after immense amounts of trials, is above 66.67% win rate, you may want to contact the makers of Let's Make a Deal, and then contact us to let us know.
DISCLAIMER: I don't think such a strategy exists, so don't lose sleep over finding it.
#!/usr/bin/python
'''
monty.py - find the probability of winning "Let's Make a Deal" given a constant strategy
Usage: monty.py <strategy> <iterations>
<strategy> is either 1, 2 or 3: 1 is 'always switch' and 2 is 'always stay'. 3 is 'switch 33% of the time'.
<iterations> is the number of times to try.
'''
import sys, random
def switch(one, two):
if one == two:
raise ValueError('You can\'t use this method with two of the same value.')
choice = 3 - one - two
return choice
strategy = int(sys.argv[1])
number = int(sys.argv[2])
wins = 0
total = 0
for i in range(number):
door = random.randrange(3)
choice = random.randrange(3)
if door == choice:
if choice == 0:
remove = random.randrange(1,3)
elif choice == 2:
remove = random.randrange(0,3,2)
else:
remove = random.randrange(0,2)
else:
remove = 3 - door - choice
if strategy == 1:
choice = switch(choice, remove)
elif strategy == 2:
choice = choice
elif strategy == 3:
if random.randrange(0,3) == 0:
choice = switch(choice, remove)
else:
raise ValueError('The strategy must be 1, 2, or 3!')
if choice == door:
wins += 1
total += 1
print "Out of %i games, your strategy won %i times." % (total, wins)
print "That is a win probability of %.2F percent." % ((float(wins) / float(total)) * 100)
@toqueteos
Copy link

monty.py line 17, quote consistency.

@MarkTraceur
Copy link
Author

Bugger all, I need to test when I change things. Sorry!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment