Instantly share code, notes, and snippets.

# MarkTraceur/ANALYSIS Created Aug 26, 2011

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 is either 1, 2 or 3: 1 is 'always switch' and 2 is 'always stay'. 3 is 'switch 33% of the time'. 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)

### Tordek commented Aug 26, 2011

 ``````elif strategy == 3: if random.randrange(0,3) == 0: choice = switch(choice, remove) else: raise ValueError('The strategy must be either 1 or 2!') `````` Outdated assertion message.
Owner Author

### MarkTraceur commented Aug 26, 2011

 At first I wondered when Python's rules on errors changed. It's fixed now.

### daniel-kullmann commented Aug 26, 2011

 ```remove = range(3) remove.remove(choice) remove.remove(door) remove = remove[0] ``` can be replaced by `remove = 3 - choice - door`
Owner Author

### MarkTraceur commented Aug 26, 2011

 Not if door == choice, but I get the idea. I never thought of it! Thanks, I'll implement it.

### toqueteos commented Aug 26, 2011

 monty.py line 17, quote consistency.
Owner Author

### MarkTraceur commented Aug 26, 2011

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