Joined January 2017
·

randrewnichol

Student - UCB
·
California
·
·

Posted to The Monty Hall Problem in Python over 1 year ago

Here's mine, yours is a bit fancier!
Functions:

#monty_hall.py
def gen_doors():
    doors = [0,1,2]
    car = random.randrange(3)
    doors[car] = "Car"
    goats = list(range(3))
    del goats[car]
    for i in goats:
        doors[i] = "Goat"
    return doors

def random_play(doors = ["Goat","Car","Goat"], switch = True):
    goats = []
    [goats.append(i) for i in range(3) if doors[i] == "Goat"]
    pick = random.randrange(3)
    if switch == True:
        if pick in goats:
            return "Car"
        else: return "Goat"
    else:
        if pick in goats:
            return "Goat"
        else: return "Car"
#sim.py
import monty_hall
plays = 100000

# With Switch:
n_goats = 0
n_cars = 0
for i in range(plays):
    if monty_hall.random_play(monty_hall.gen_doors(), True) == "Goat": n_goats += 1
    else: n_cars += 1
print("With Switching:\nGoats: ", n_goats, "\n", "Cars: ", n_cars, "\n")

n_goats = 0
n_cars = 0
# Without Switch:
for i in range(plays):
    if monty_hall.random_play(monty_hall.gen_doors(), False) == "Goat": n_goats +=1
    else: n_cars +=1
print("Without Switching:\nGoats: ", n_goats, "\n", "Cars: ", n_cars)

[Out]
With Switching:
Goats: 33210
Cars: 66790

Without Switching:
Goats: 66812
Cars: 33188

Achievements
1 Karma
0 Total ProTip Views
Interests & Skills