Skip to content

Instantly share code, notes, and snippets.

@ojas
Created February 9, 2015 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ojas/5129c5093e6629cfb9f5 to your computer and use it in GitHub Desktop.
Save ojas/5129c5093e6629cfb9f5 to your computer and use it in GitHub Desktop.
Monty Hall
{
"metadata": {
"name": "",
"signature": "sha256:54dd0380143918c25eba34914e70f3100831189ab021b2871dcf92f0b5cce9d3"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"#!/usr/bin/env python\n",
"\n",
"from random import randint, sample\n",
"\n",
"def simulate_once(switch_door):\n",
" picked_door = randint(0, 2)\n",
" door_with_prize = randint(0, 2)\n",
"\n",
" # If picked_door == door_with_prize, there are 2 doors he can choose to open\n",
" # otherwise, there's only one.\n",
" doors_monty_can_open = set(n for n in range(3) if n not in (picked_door, door_with_prize))\n",
" door_monty_opens = sample(doors_monty_can_open, 1)[0]\n",
" \n",
" if switch_door:\n",
" picked_door = list(n for n in range(3) if n not in (picked_door, door_monty_opens))[0]\n",
"\n",
" return picked_door == door_with_prize\n",
"\n",
"def main():\n",
" n_runs = 100000\n",
" n_wins = 0\n",
" for i in range(1, n_runs):\n",
" if simulate(False):\n",
" n_wins += 1\n",
"\n",
" print 'WITHOUT switching', 1.* n_wins/n_runs\n",
" n_wins = 0\n",
" for i in range(1, n_runs):\n",
" if simulate(True):\n",
" n_wins += 1\n",
"\n",
" print 'WITH switching', 1.* n_wins/n_runs\n",
"\n",
"if __name__ == \"__main__\":\n",
" main()\n",
"\n"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"WITHOUT switching 0.33341\n",
"WITH switching"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
" 0.66832\n"
]
}
],
"prompt_number": 86
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment