Chi-Square: Observed Counts vs Expected Counts

Probability and StatisticsMedium+15 XP+15

Chi-Square: Observed Counts vs Expected Counts

You have a table of counts — say rows for "saw the ad" / "didn't" and columns for "bought" / "didn't buy". The question is whether the two things are related, or whether the pattern is what you'd expect from pure chance.

The chi-square test answers it by comparing what you observed against what you'd expect if the rows and columns had nothing to do with each other.

For the cell in row i, column j:

Eij=(total of row i)×(total of column j)grand totalE_{ij} = \frac{(\text{total of row } i) \times (\text{total of column } j)}{\text{grand total}}Eij​=grand total(total of row i)×(total of column j)​

Then add up, over every cell:

χ2=∑(Oij−Eij)2Eij\chi^2 = \sum \frac{(O_{ij} - E_{ij})^2}{E_{ij}}χ2=∑Eij​(Oij​−Eij​)2​

Task: write chi2_statistic(table) returning [chi2, dof] — the statistic rounded to 4 decimal places, and the degrees of freedom as a plain integer:

dof=(rows−1)×(columns−1)\text{dof} = (\text{rows} - 1) \times (\text{columns} - 1)dof=(rows−1)×(columns−1)
  • table is a list of rows of counts, at least 2×2, and every row has the same length.
  • Every expected count is above zero, so you never divide by zero.
  • Divide by the expected count, not the observed one. That's what turns a raw gap into a fair comparison: being 10 off when you expected 20 is a scandal, being 10 off when you expected 1000 is nothing.

A big statistic means observation and expectation disagree, so the two variables probably are related.

Examples

table = [[20, 30], [30, 20]]
returns [4.0, 1]
table = [[25, 25], [25, 25]]
returns [0.0, 1]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run