# Monty Hall Simulator

May 14th, 2021
793
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. from random import randint, random, choice
2.
3. class MontyHallDoors():
4.     def __init__(self):
5.         self.doors = [0 for i in range(3)]
6.         self.car_door = randint(0,2)
7.         self.doors[self.car_door] = 1
8.
9.     def is_car_door(self,i):
10.         return self.doors[i] == 1
11.
12.     def get_car_door(self):
13.         return self.car_door
14.
15.     def __str__(self):
16.         l = []
17.         for i in range(3):
18.             if self.is_car_door(i):
19.                 l.append("car")
20.             else:
21.                 l.append("goat")
22.         return "[{}, {}, {}]".format(l[0],l[1],l[2])
23.
24. stay_attempts = []
25. switch_attempts = []
26.
27. for i in range(100000):
28.     monty = MontyHallDoors()
29.
30.     car_door = monty.get_car_door()
31.
32.     # pick first door for the contestant
33.     first_door = randint(0,2)
34.
35.     # offer the switch
36.     if(first_door == car_door):
37.         open_door = choice([i for i in range(3) if i != first_door])
38.     else:
39.         open_door = 3 - first_door - car_door
40.
41.     offered_door = 3 - first_door - open_door
42.
43.     # pick your strategy: stay or switch
44.     stay_mode = random() <= 0.5
45.
46.     # do the switch if decided to
47.     chosen_door = offered_door if not stay_mode else first_door
48.
49.     # check if door is correct and append to the correct strat
50.     if(stay_mode):
51.         stay_attempts.append(car_door == chosen_door)
52.     else:
53.         switch_attempts.append(car_door == chosen_door)
54.
55.     #print(monty)
56.     #print("Mode: {}".format("stay" if stay_mode else "switch"))
57.     #print("first door: {}".format(first_door))
58.     #print("final door: {}".format(chosen_door))
59.     #print("Result: {}".format("Win" if car_door == chosen_door else "lose"))
60.
61. stay_winning_chance = 1.0*len([0 for i in range(len(stay_attempts)) if stay_attempts[i]])/len(stay_attempts)
62.
63. switch_winning_chance = 1.0*len([0 for i in range(len(switch_attempts)) if switch_attempts[i]])/len(switch_attempts)
64.
65. print(stay_winning_chance, switch_winning_chance)
RAW Paste Data