Two treatments were tried in several groups. Report success rates within each group and overall, and say whether the combined data reverse the group-level result.
What to build
A program that compares two treatments within groups and overall and detects Simpson's paradox.
Requirements
- For each group, in order of first appearance, print
GROUP: A X%, B Y%, with rates to one decimal place. - Then print
overall: A X%, B Y%. - Finally print
paradox: yesif one treatment has the strictly higher rate in every group while the other has the strictly higher overall rate; otherwiseparadox: no.
Input
Line 1: n. Then n lines GROUP,TREATMENT,SUCCESSES,TOTAL, where TREATMENT is A or B; every group has exactly one A line and one B line.
Output
One line per group, then two lines.
Constraints
1 to 20 groups; 1 ≤ TOTAL ≤ 100000; 0 ≤ SUCCESSES ≤ TOTAL.
Example
Input:
4
small,A,81,87
small,B,234,270
large,A,192,263
large,B,55,80
Output:
small: A 93.1%, B 86.7%
large: A 73.0%, B 68.8%
overall: A 78.0%, B 82.6%
paradox: yes
Why it works
Overall rates weight each group by how many cases it has, so a treatment given mostly to hard cases can win in every group and still lose overall; checking both levels exposes it.
Examples
4 small,A,81,87 small,B,234,270 large,A,192,263 large,B,55,80
small: A 93.1%, B 86.7% large: A 73.0%, B 68.8% overall: A 78.0%, B 82.6% paradox: yes
4 g1,A,8,10 g1,B,6,10 g2,A,5,10 g2,B,3,10
g1: A 80.0%, B 60.0% g2: A 50.0%, B 30.0% overall: A 65.0%, B 45.0% paradox: no
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep, for each group, the successes and totals of A and B; also keep running overall totals.
Hint 2
Remember the groups in the order they first appear.
Hint 3
The paradox needs the same treatment strictly better in every group and the other strictly better overall.
Solution
Show one correct solution (try it yourself first)
n = int(input())
groups, order = {}, []
overall = {"A": [0, 0], "B": [0, 0]}
for _ in range(n):
g, t, s, total = input().split(",")
if g not in groups:
groups[g] = {}
order.append(g)
groups[g][t] = (int(s), int(total))
overall[t][0] += int(s)
overall[t][1] += int(total)
def rate(pair):
return 100 * pair[0] / pair[1]
a_wins = b_wins = 0
for g in order:
ra, rb = rate(groups[g]["A"]), rate(groups[g]["B"])
print(f"{g}: A {ra:.1f}%, B {rb:.1f}%")
a_wins += ra > rb
b_wins += rb > ra
oa, ob = rate(overall["A"]), rate(overall["B"])
print(f"overall: A {oa:.1f}%, B {ob:.1f}%")
paradox = (a_wins == len(order) and ob > oa) or (b_wins == len(order) and oa > ob)
print("paradox:", "yes" if paradox else "no")