A recent post on Twitter contained a probability challenge:
I’ve fallen in love with the Monte Carlo method of using computers to simulate repeated random experiments. It’s a great way to get to the heart of what’s happening in a probability problem. It’s like being able to flip a coin or roll a die a million times using a computer. I went to work modeling the situation in Python:
from random import random N_TRIALS = 1000000 trialList =  #empty list for all the trials for i in range(N_TRIALS): trial =  # single Trial randA = random() #generate a couple of random numbers randB = random() if randA <= 0.2: #if A is successful: trial.append(1) #add it to the trial else: trial.append(0) if randB <= 0.3: #same with B trial.append(1) else: trial.append(0) #so that's going to be like [1,0] or [1,1] for example trialList.append(trial) #add the trial to the trialList
So now we’ll have a million random trials. We’ll check for the ones in which A succeeded but B didn’t and so on. Now all we have to do is check for each possibility and we should get close to the real probability:
As = 0 #number of times A occurs Bs = 0 #number of times B occurs Cs = 0 #at least 1 of A or B Ds = 0 #exactly 1 of A or B A_given_D = 0 B_given_D = 0 #iterate over trialList and sum up the scores for trial in trialList: if trial: #[1,0] or [1,1] As += 1 if trial: #[0,1] or [1,1] Bs += 1 if 1 in trial: #[0,1],[1,0] or [1,1] Cs += 1 if sum(trial) == 1: #[0,1] or [1,0] Ds += 1 if trial: #[1,0] A_given_D += 1 if trial: #[0,1] B_given_D += 1 P_D = Ds/N_TRIALS #print the results print("P(A):",As/N_TRIALS) print("P(B):",Bs/N_TRIALS) print("P(C):",Cs/N_TRIALS) print("P(Exactly 1):",P_D) print("P(A|D):",(A_given_D/(N_TRIALS*P_D))) print("P(B|D):",B_given_D/(N_TRIALS*P_D))
The outcome is given below. The Center of Math posted the answers and mine came very close!
Results: P(A): 0.1994 P(B): 0.2996 P(C): 0.4393 P(Exactly 1): 0.3794 P(A|D): 0.3679 P(B|D): 0.6320