Update a discrete posterior over hypotheses after each observation

Why it matters Discrete Bayes updates power spam filters, diagnostic tests, A/B test reasoning and the belief tracking inside many agents and robots.

Bayes' rule turns a prior belief and evidence into a posterior. With a few discrete hypotheses it is just multiply and normalise.

Write discrete_posterior(prior, likelihood, observations). prior has length H. likelihood is an (H, K) table where likelihood[h][k] = P(observation k | hypothesis h). observations is a list of observation indices, assumed independent given the hypothesis. Return the posterior after all observations as a float array of length H. Normalise after each observation.

Signaturedef discrete_posterior(prior, likelihood, observations)

Example

prior [0.5, 0.5], likelihood [[0.5, 0.5], [0.9, 0.1]] (a fair coin and a coin biased to heads, observation 0 = heads), observations [0, 0, 0] gives [0.14637, 0.85363] (rounded).

Understand the idea

Bayes' rule says: new belief is proportional to old belief times how well each hypothesis explains what you saw.

Worked example: a bag has two coins, one fair and one that lands heads 90% of the time. You pick one at random (prior 0.5 each) and see heads. Fair coin: 0.5 * 0.5 = 0.25. Biased coin: 0.5 * 0.9 = 0.45. Normalising gives 0.357 and 0.643. After a second heads: 0.357 * 0.5 and 0.643 * 0.9, which normalise to 0.236 and 0.764. Each heads pushes belief toward the biased coin.

Rule: posterior(h) = prior(h) * product over observations of P(obs | h), divided by the sum over all h.

The prior matters. If biased coins are rare (prior 0.05), three heads in a row still leave the fair coin more likely. This is the classic base-rate lesson from medical tests. The same multiply-and-normalise loop is used in spam filtering and in tracking an agent's belief about hidden state.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplediscrete_posterior([0.5, 0.5], [[0.5, 0.5], [0.9, 0.1]], [0, 0, 0])
  • Sample 2: strong priordiscrete_posterior([0.95, 0.05], [[0.5, 0.5], [0.9, 0.1]], [0, 0, 0])
  • Test 3: three hypothesesdiscrete_posterior([0.2, 0.5, 0.3], [[0.7, 0.2, 0.1], [0.3, 0.4, 0.3], [0.1, 0.2, 0.7]], [2, 2, 1])
  • Test 4: no datadiscrete_posterior([0.1, 0.9], [[0.5, 0.5], [0.2, 0.8]], [])