A test of independence

A survey cross-tabulates two categorical answers, such as age group and preferred app. Test whether the two are independent at the 5% level.

What to build

A program that prints the expected table, the chi-square statistic and the decision.

Requirements

  • Print one line per row: expected followed by the row's expected counts, each to 2 decimal places, separated by spaces.
  • Then print chi-square X (3 decimal places), df D and critical C (3 decimal places).
  • Finally print reject H0 when the statistic is over the critical value, otherwise keep 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

The first line has r and c; each of the next r lines has c counts.

Output

r lines, then four lines.

Constraints

2 ≤ r, c; (r − 1)(c − 1) ≤ 10; every row and column total is over 0.

Example

Input:

2 2
30 10
20 40

Output:

expected 20.00 20.00
expected 30.00 30.00
chi-square 16.667
df 1
critical 3.841
reject H0

Why it works

If the variables are independent, a cell's share of the total is its row share times its column share, which gives row total × column total ÷ grand total as the expected count.

Examples

Example 1 · Input
2 2
30 10
20 40
Expected output
expected 20.00 20.00
expected 30.00 30.00
chi-square 16.667
df 1
critical 3.841
reject H0
Example 2 · Input
2 3
10 20 30
10 20 30
Expected output
expected 10.00 20.00 30.00
expected 10.00 20.00 30.00
chi-square 0.000
df 2
critical 5.991
keep H0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Work out the row totals, the column totals and the grand total first.

Hint 2

The expected count of cell (i, j) is row[i] × col[j] ÷ total.

Hint 3

df = (r − 1)(c − 1); look up its critical value as in the previous exercise.

Solution

Show one correct solution (try it yourself first)
r, c = map(int, input().split())
t = [list(map(float, input().split())) for _ in range(r)]
rows = [sum(row) for row in t]
cols = [sum(t[i][j] for i in range(r)) for j in range(c)]
total = sum(rows)
chi = 0
for i in range(r):
    exp = [rows[i] * cols[j] / total for j in range(c)]
    print("expected", " ".join(f"{e:.2f}" for e in exp))
    chi += sum((t[i][j] - exp[j]) ** 2 / exp[j] for j in range(c))
crit = [3.841, 5.991, 7.815, 9.488, 11.070, 12.592, 14.067, 15.507, 16.919, 18.307]
df = (r - 1) * (c - 1)
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")

Lesson: Chi-square tests for counts →