Created
March 13, 2014 21:27
-
-
Save ydm/9537323 to your computer and use it in GitHub Desktop.
Monty Hall problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import random | |
import multiprocessing | |
def gen_case(): | |
return ['goat' if e else 'car' for e in random.sample(range(3), 3)] | |
def open_goat(case, choice): | |
for i, e in enumerate(case): | |
if i != choice and e == 'goat': | |
return i | |
def solve(switch): | |
"""Return True if you win the car.""" | |
case = gen_case() | |
choice = random.randint(0, 2) | |
goat = open_goat(case, choice) | |
other = (set([choice, goat]) ^ set(range(3))).pop() | |
return case[other if switch else choice] == 'car' | |
def probability(runs, switch): | |
wins = 0 | |
for _ in range(runs): | |
wins += solve(switch) | |
print('probability={}, switch={}'.format(float(wins) / runs * 100, switch)) | |
def main(): | |
t = multiprocessing.Process(target=probability, args=[100000, True]) | |
t.start() | |
probability(100000, False) | |
t.join() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment