KatInterview

Posterior Probability of Facility Given Red Samples

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingprobabilitybayes-theoremmathematical-reasoning

Last updated

Tests Bayesian reasoning: computing the posterior probability of a hypothesis using likelihoods and equal priors.

Two manufacturing facilities produce identical components in red and black colors.

  • Facility 1 outputs a percent red parts and (100-a) percent black parts.
  • Facility 2 outputs b percent red parts and (100-b) percent black parts.

You randomly choose one facility with equal probability (50% chance for each) and draw k parts from it. All k parts are red.

Calculate the probability that you chose Facility 1, given this observation.

Input

  • a: integer percentage (0-100) of red parts produced by Facility 1
  • b: integer percentage (0-100) of red parts produced by Facility 2
  • k: positive integer, number of parts drawn

Output

Return a float: the conditional probability that Facility 1 was chosen, given that all k drawn parts are red.

Constraints

  • 0 ≤ a ≤ 100
  • 0 ≤ b ≤ 100
  • k ≥ 1
  • Each facility has unlimited parts; treat successive draws as independent
  • If both facilities cannot produce red parts (a = 0 and b = 0), return 0.0
  • If both facilities have the same red rate (a = b), return 0.5 (the prior remains unchanged)

Examples

Example 1

Input: facility_posterior(60, 40, 1)

Output: 0.6

Example 2

Input: facility_posterior(60, 40, 2)

Output: 0.6923076923076923

Example 3

Input: facility_posterior(30, 70, 3)

Output: 0.07297297297297299

Hints

Hint 1

Apply Bayes' theorem: the posterior probability is proportional to the likelihood times the prior.

Hint 2

The probability of drawing k red parts from a facility with red rate p is p^k.

Hint 3

Since both facilities start with equal probability, the posterior ratio depends only on the likelihood ratio.