A two-way table of counts holds every conditional probability you need. Read two of them, in both directions.
What to build
A program that prints P(A | B) and P(B | A) from a 2 by 2 table.
Requirements
- The input is the four counts a (A and B), b (A and not B), c (not A and B) and d (not A and not B).
- Print
P(A|B) = XandP(B|A) = Yas reduced fractions.
Input
One line: a, b, c and d.
Output
Two lines.
Constraints
All counts are whole numbers from 0 to 10000; a + b and a + c are both more than 0.
Example
Input:
30 10 24 36
Output:
P(A|B) = 5/9
P(B|A) = 3/4
Why it works
A condition shrinks the world to one row or one column, so each conditional probability divides the shared count by a different total, which is why the two directions differ.
Examples
Example 1 · Input
30 10 24 36
Expected output
P(A|B) = 5/9 P(B|A) = 3/4
Example 2 · Input
1 1 1 1
Expected output
P(A|B) = 1/2 P(B|A) = 1/2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
P(A | B) divides the "A and B" count by everyone in B: a ÷ (a + c).
Hint 2
P(B | A) divides by everyone in A instead: a ÷ (a + b).
Solution
Show one correct solution (try it yourself first)
from fractions import Fraction
a, b, c, d = map(int, input().split())
print("P(A|B) =", Fraction(a, a + c))
print("P(B|A) =", Fraction(a, a + b))