A die, a spinner or a set of survey options is supposed to give every outcome equally often. Test it with a chi-square goodness-of-fit test at the 5% level.
What to build
A program that tests whether k categories are equally likely.
Requirements
- Print
expected E(2 decimal places),chi-square X(3 decimal places),df Dandcritical C(3 decimal places). - Then print
reject H0when the statistic is over the critical value, otherwisekeep H0. - Use the 5% critical values 3.841, 5.991, 7.815, 9.488, 11.070, 12.592, 14.067, 15.507, 16.919 and 18.307 for df 1 to 10.
Input
One line: the observed counts.
Output
Five lines.
Constraints
2 to 11 categories; the total is over 0.
Example
Input:
8 9 12 11 6 14
Output:
expected 10.00
chi-square 4.200
df 5
critical 11.070
keep H0
Why it works
With the total fixed, only k − 1 counts can vary freely, so the statistic is compared with the chi-square curve for k − 1 degrees of freedom.
Examples
Example 1 · Input
8 9 12 11 6 14
Expected output
expected 10.00 chi-square 4.200 df 5 critical 11.070 keep H0
Example 2 · Input
30 20
Expected output
expected 25.00 chi-square 2.000 df 1 critical 3.841 keep H0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Under H₀ every category expects total ÷ k.
Hint 2
df = k − 1; keep the 5% critical values in a list indexed by df.
Solution
Show one correct solution (try it yourself first)
obs = list(map(float, input().split()))
k = len(obs)
e = sum(obs) / k
chi = sum((o - e) ** 2 / e for o in obs)
crit = [3.841, 5.991, 7.815, 9.488, 11.070, 12.592, 14.067, 15.507, 16.919, 18.307]
df = k - 1
print(f"expected {e:.2f}")
print(f"chi-square {chi:.3f}")
print(f"df {df}")
print(f"critical {crit[df - 1]:.3f}")
print("reject H0" if chi > crit[df - 1] else "keep H0")