Bayesian Origin Probability for Sampled Items
Arrays & HashingAuto-graded · 17 test casesLast updated
Calculate the posterior probability that two black items came from a specific facility using Bayes' Theorem.
Facility A produces items that are 40% red and 60% black. Facility B produces items that are 80% red and 20% black.
One facility is selected uniformly at random. Then, two items are sampled independently and uniformly at random from that chosen facility.
Given that both drawn items turn out to be black, calculate the posterior probability that the chosen facility was Facility A.
Constraints
- Assume ideal independent draws with replacement (or an infinite production volume).
- Return the exact calculated probability as a float.
Examples
Example 1
Input: calculate_facility_a_probability()
Output: 0.8999999999999999
Hints
Hint 1
Use Bayes' Theorem: P(Facility A | 2 Black) = P(2 Black | Facility A) * P(Facility A) / P(2 Black).
Hint 2
Because draws are independent given the facility, P(2 Black | Facility) is equal to the single-item black rate squared.
Hint 3
Since both facilities are initially chosen with equal probability (0.5), the prior probabilities cancel out.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To find the probability that the items originated from Facility A given that both sampled items are black ($BB$), we apply Bayes' Theorem:
$$P(A \mid BB) = \frac{P(BB \mid A) \cdot P(A)}{P(BB)}$$
-
Prior Probabilities: Since one facility is selected uniformly at random, $P(A) = P(B) = 0.5$.
-
Likelihoods: The probability of an item being black at Facility A is $1 - 0.40 = 0.60$. The probability of an item being black at Facility B is $1 - 0.80 = 0.20$.
Assuming independent draws given the selected facility:
- $P(BB \mid A) = 0.60^2 = 0.36$
- $P(BB \mid B) = 0.20^2 = 0.04$
-
Total Probability: By the law of total probability: $$P(BB) = P(BB \mid A) \cdot P(A) + P(BB \mid B) \cdot P(B)$$ $$P(BB) = 0.36 \cdot 0.5 + 0.04 \cdot 0.5 = 0.18 + 0.02 = 0.20$$
-
Posterior Probability: $$P(A \mid BB) = \frac{0.18}{0.20} = 0.9$$
Because the priors $P(A)$ and $P(B)$ are equal, they cancel out, simplifying the calculation to $\frac{0.36}{0.36 + 0.04} = 0.9$.
Complexity Analysis
- Time Complexity: $\mathcal{O}(1)$ since the solution involves basic floating-point arithmetic operations.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space.
def calculate_facility_a_probability() -> float:
# Black item probability for each facility
p_black_a = 0.6
p_black_b = 0.2
# Likelihood of drawing two black items independently
likelihood_a = p_black_a ** 2
likelihood_b = p_black_b ** 2
# Bayes' Theorem with uniform priors P(A) = P(B) = 0.5
# P(A | 2 Black) = likelihood_a / (likelihood_a + likelihood_b)
return likelihood_a / (likelihood_a + likelihood_b)