A patient takes the same test several times. Update the probability of illness after each result, using each answer as the next prior.
What to build
A program that applies Bayes' theorem once per test result.
Requirements
- The test has a sensitivity (P(positive | sick)) and a specificity (P(negative | healthy)); results are independent given the patient's state.
- For each result print
after R: Pwith R the result (+or-) and P the probability of illness so far, to 4 decimal places.
Input
Line 1: the prior, the sensitivity and the specificity. Line 2: the results, + or -, separated by spaces.
Output
One line per result.
Constraints
1 to 20 results; the numbers are decimals from 0 to 1, and no denominator is 0.
Example
Input:
0.01 0.99 0.95
+ +
Output:
after +: 0.1667
after +: 0.7984
Why it works
Each result is evidence that Bayes' theorem combines with the current belief, so the posterior after one test is the prior for the next, and repeated positives quickly overcome a low base rate.
Examples
0.01 0.99 0.95 + +
after +: 0.1667 after +: 0.7984
0.5 0.8 0.9 - +
after -: 0.1818 after +: 0.6400
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
After a positive: p × sens ÷ (p × sens + (1 − p) × (1 − spec)).
Hint 2
After a negative: p × (1 − sens) ÷ (p × (1 − sens) + (1 − p) × spec). The new p is the prior for the next result.
Solution
Show one correct solution (try it yourself first)
p, sens, spec = map(float, input().split())
for r in input().split():
if r == "+":
yes, no = p * sens, (1 - p) * (1 - spec)
else:
yes, no = p * (1 - sens), (1 - p) * spec
p = yes / (yes + no)
print(f"after {r}: {p:.4f}")