#109Chi-Square Test of IndependenceMediumStatisticsAsked atMicrosoft · Meta · Google
Chi-Square Test of Independence
Background
The chi-square test of independence asks whether two categorical variables (e.g. arm vs converted) are statistically independent. It compares the observed contingency-table counts to those expected under independence; large discrepancies imply dependence.
Problem statement
Implement chi_square_independence(observed) returning (chi2, df) where:
Input
observed—np.ndarrayshape of non-negative integer counts.
Output
Returns a tuple (chi2: float, df: int). chi2 >= 0; df = (R-1)(C-1).
Examples
Example 1 — independent counts
Input: [[10, 20], [10, 20]]
Output: (~0.0, 1)
Explanation: rows are scaled copies of each other → exactly independent → .
Example 2 — strong dependence
Input: [[100, 0], [0, 100]]
Output: large chi2, df = 1
Example 3 — three-by-three table
Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: small chi2, df = 4
Constraints
- Cells with are skipped (otherwise dividing by zero).
- Returns plain Python
floatandint. - For small expected counts (), the chi-square approximation breaks; this problem does not enforce that — caller's responsibility.
Notes
- Yates correction. For 2×2 tables some statisticians subtract 0.5 from before squaring (Yates' continuity correction). Out of scope here.
- Reads with scipy. Combine with
scipy.stats.chi2.sf(stat, df)to get a -value.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •reference: independent counts give chi2 near zero
- •example: 3x3 table has df = (3-1)(3-1) = 4
- •sample: chi2 on [[10,20],[30,40]]