Monty Hall problem


/ Published in: Python
Save to your folder(s)

A proof of the Monty Hall problem written in Python.


Copy this code and paste it in your HTML
  1. #---------------------------------
  2. # The Monty Hall Problem
  3. #---------------------------------
  4.  
  5. import random
  6.  
  7. pickcount = 0
  8. newpickcount = 0
  9. i = 0
  10. counter = 100000
  11.  
  12. def pick1of3():
  13. pick=random.randint(0,2)
  14. return pick
  15.  
  16. while i < counter:
  17. # Prize assignment
  18. doors = ['goat','goat','goat']
  19. car = pick1of3()
  20. doors[car] = 'car '
  21.  
  22. # Contestant choice
  23. firstchoice = pick1of3()
  24. pick = doors[firstchoice]
  25.  
  26. # Monty's reveal
  27. reveal=random.random()
  28.  
  29. if firstchoice == 0:
  30. if pick=='car ' and reveal < 0.5: Montyshows=doors[1]
  31. elif pick=='car ': Montyshows=doors[2]
  32. elif pick=='goat' and doors[1]=='goat': Montyshows=doors[1]
  33. else: Montyshows=doors[2]
  34.  
  35. elif firstchoice == 1:
  36. if pick=='car ' and reveal < 0.5: Montyshows=doors[0]
  37. elif pick=='car ': Montyshows=doors[2]
  38. elif pick=='goat' and doors[0]=='goat': Montyshows=doors[0]
  39. else: Montyshows=doors[2]
  40.  
  41. elif firstchoice == 2:
  42. if pick=='car ' and reveal < 0.5: Montyshows=doors[0]
  43. elif pick=='car ': Montyshows=doors[1]
  44. elif pick=='goat' and doors[0]=='goat': Montyshows=doors[0]
  45. else: Montyshows=doors[1]
  46.  
  47.  
  48. # The Switch
  49. if pick==doors[0]:
  50. if Montyshows==doors[1]: newpick=doors[2]
  51. else: newpick=doors[1]
  52.  
  53. elif pick==doors[1]:
  54. if Montyshows==doors[0]: newpick=doors[2]
  55. else: newpick=doors[0]
  56.  
  57. else:
  58. if Montyshows==doors[0]: newpick=doors[1]
  59. else: newpick=doors[0]
  60.  
  61. if pick == 'car ':
  62. pickcount = pickcount + 1
  63.  
  64. if newpick == 'car ':
  65. newpickcount = newpickcount + 1
  66.  
  67. i = i + 1
  68.  
  69. print 'Original Pick is a Car: ',"{0:.3f}%".format(float(pickcount)/counter * 100)
  70. print 'Switched Pick is a Car: ',"{0:.3f}%".format(float(newpickcount)/counter * 100)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.