KatInterview

Calculate Bag Selection Probability via Bayes' Theorem

Math & Bit ManipulationAuto-graded · 16 test cases
EasyAuto-gradedMath & Bit Manipulationmathprobabilitybayes-theorem

Last updated

Given selection priors and ball counts for several containers, calculate the posterior probability of drawing from a specific container after observing a target outcome.

You are analyzing a set of containers, each filled with two types of objects: target objects (e.g., red balls) and non-target objects.

You are given three arrays of equal length representing the contents and selection probabilities of these containers:

  1. red_counts: An array of integers where red_counts[i] represents the number of target objects in container $i$.
  2. total_counts: An array of integers where total_counts[i] represents the total number of objects in container $i$.
  3. priors: An array of numbers where priors[i] represents the prior probability of selecting container $i$. Note that priors do not necessarily sum to 1.0; they should be treated as proportional weights.

A container is selected at random according to the given priors, and then one object is drawn uniformly at random from that container.

Given that the selected object is a target object (red), compute the posterior probability that it originated from container index 1 (the second container, equivalent to "Bag B").

Constraints

  • len(red_counts) == len(total_counts) == len(priors)
  • len(red_counts) >= 2
  • $0 \le \text{red_counts}[i] \le \text{total_counts}[i]$
  • $\text{total_counts}[i] > 0$ for all $i$.
  • $\text{priors}[i] \ge 0$ for all $i$, and at least one container with $\text{red_counts}[i] > 0$ has $\text{priors}[i] > 0$.

Examples

Example 1

Input: posterior_b_probability([4, 6, 3], [10, 10, 10], [1, 1, 1])

Output: 0.4615384615384615

Example 2

Input: posterior_b_probability([4, 6, 3], [10, 10, 10], [0.2, 0.5, 0.3])

Output: 0.6382978723404256