This is for homework but the deadline is over and I know the implementation is correct because it concurs with the math. At this point I just want to check my implementation for potential optimizations in terms of speed, memory usage, clarity, modularity, and anything else you guys might think of. (I know there is generally a trade-off between computation speed and memory usage, so if you have comments on that I appreciate any insight you might have)
The specs of the function are that it should be flexible as to how many doors and trials we want, and whether or not we're switching doors. We also assume that the guest always chooses the first door. This is the only non-variable component we're allowed.
For example, would using np.array
make the code faster than using lists? I didn't think it'd make a difference because they're very small, but that could be wrong.
In general, what could I do better?
def monty_hall (num_doors, trials, switch):
#count number of successful trials
successes = 0
for i in range(trials):
#determine behind which door the prize is
doors = [i for i in range(1, num_doors+1)]
prize_door = np.random.choice(doors)
#determine which door the host opens if guest switches
host_doors = [i for i in range(2, num_doors+1)]
if prize_door != 1:
host_doors.remove(prize_door)
host_choice = np.random.choice(host_doors)
#determine which door the guest chooses if switching
doors.remove(1); doors.remove(host_choice)
guest_switch = np.random.choice(doors)
#we assume the guest is always choosing the first door
if prize_door == 1 and switch == 0:
successes += 1
elif prize_door != 1 and switch:
if guest_switch == prize_door:
successes += 1
probability = successes / trials
return probability