aly revised this gist . Go to revision
1 file changed, 53 insertions
montyhall.py(file created)
| @@ -0,0 +1,53 @@ | |||
| 1 | + | import random | |
| 2 | + | ||
| 3 | + | def run_trial(switch_doors, ndoors=3): | |
| 4 | + | """ | |
| 5 | + | Run a single trial of the Monty Hall problem, with or without switching | |
| 6 | + | after the gameshow host reveals a goat behind one of the unchosen doors. | |
| 7 | + | (switch_doors is True or False). The car is behind door number 1 and the | |
| 8 | + | gameshow host knows that. | |
| 9 | + | ||
| 10 | + | """ | |
| 11 | + | ||
| 12 | + | # Pick a random door out of the ndoors available | |
| 13 | + | chosen_door = random.randint(1, ndoors) | |
| 14 | + | if switch_doors: | |
| 15 | + | # Reveal a goat | |
| 16 | + | revealed_door = 3 if chosen_door==2 else 2 | |
| 17 | + | # Make the switch by choosing any other door than the initially- | |
| 18 | + | # selected one and the one just opened to reveal a goat. | |
| 19 | + | available_doors = [dnum for dnum in range(1,ndoors+1) | |
| 20 | + | if dnum not in (chosen_door, revealed_door)] | |
| 21 | + | chosen_door = random.choice(available_doors) | |
| 22 | + | ||
| 23 | + | # You win if you picked door number 1 | |
| 24 | + | return chosen_door == 1 | |
| 25 | + | ||
| 26 | + | def run_trials(ntrials, switch_doors, ndoors=3): | |
| 27 | + | """ | |
| 28 | + | Run ntrials iterations of the Monty Hall problem with ndoors doors, with | |
| 29 | + | and without switching (switch_doors = True or False). Returns the number | |
| 30 | + | of trials which resulted in winning the car by picking door number 1. | |
| 31 | + | ||
| 32 | + | """ | |
| 33 | + | ||
| 34 | + | nwins = 0 | |
| 35 | + | for i in range(ntrials): | |
| 36 | + | if run_trial(switch_doors, ndoors): | |
| 37 | + | nwins += 1 | |
| 38 | + | return nwins | |
| 39 | + | ||
| 40 | + | sw,nosw = [],[] | |
| 41 | + | from time import sleep | |
| 42 | + | from sys import stderr | |
| 43 | + | try: | |
| 44 | + | while True: | |
| 45 | + | ndoors, ntrials = 3, 10000 | |
| 46 | + | nwins_without_switch = run_trials(ntrials, False, ndoors) | |
| 47 | + | nwins_with_switch = run_trials(ntrials, True, ndoors) | |
| 48 | + | sw.append(nwins_with_switch/ntrials) | |
| 49 | + | nosw.append(nwins_without_switch/ntrials) | |
| 50 | + | print("switch: {:.04f} ({:.04f}) noswch: {:.04f} ({:.04f})".format(sw[-1],sum(sw)/len(sw),nosw[-1],sum(nosw)/len(nosw)),file=stderr) | |
| 51 | + | sleep(0.001) | |
| 52 | + | except KeyboardInterrupt: | |
| 53 | + | print(sw,nosw) | |
Newer
Older