Skip to content

Instantly share code, notes, and snippets.

@suzaku
Created May 26, 2015 08:15
Show Gist options
  • Save suzaku/8be8250980e9da7e18cf to your computer and use it in GitHub Desktop.
Save suzaku/8be8250980e9da7e18cf to your computer and use it in GitHub Desktop.
Simulation of the Monty Hall problem
import random
def setup_doors():
doors = [0] * 3
doors[random.choice(range(3))] = 1
return doors
def select():
return random.choice(range(3))
def reveal_goat(doors, selected):
candidates = [i for i, v in enumerate(doors) if i != selected and v == 0]
return random.choice(candidates)
def win_after_switch():
doors = setup_doors()
selected = select()
revealed = reveal_goat(doors, selected)
switch_to = ({0, 1, 2} - {selected, revealed}).pop()
return doors[switch_to] == 1
if __name__ == '__main__':
print(sum(1 for i in xrange(100000) if win_after_switch()))
@suzaku
Copy link
Author

suzaku commented May 26, 2015

In [42]: 2.0 / 3
Out[42]: 0.6666666666666666

In [43]: sum(1 for i in xrange(10000) if play())
Out[43]: 6684

In [44]: sum(1 for i in xrange(10000) if play())
Out[44]: 6732

In [45]: sum(1 for i in xrange(10000) if play())
Out[45]: 6666

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