Problem 356240 · easy · Level 03 Linear Management & Searching

If They Were Independent

independence · two-way table · expected counts · multiplication rule

A market stall records, for each customer, their age group (the rows) and how they paid (the columns). The table is a dictionary of dictionaries: table[row][col] is a count, and every row has the same column names.

If age group and payment method were independent, then for every cell P(row and col) = P(row) · P(col), so the cell's count would be

expected = row total × column total / grand total

Write independence_check(table) that returns a tuple (independent, row, col, expected):

  • independent is True when every cell's count equals its expected count exactly, and False otherwise;
  • (row, col) is the cell whose count is farthest from its expected count (largest absolute difference). On a tie, the first such cell wins, going through the rows in the order of the dictionary and, within a row, through the columns in order;
  • expected is that cell's expected count, as a float.

Examples

Input:  table = {"under 30": {"card": 30, "cash": 10},
                 "30-60":    {"card": 45, "cash": 15},
                 "over 60":  {"card": 15, "cash": 25}}
Output: (False, "over 60", "card", 25.714285714285715)
Explanation: 90 of the 140 customers paid by card, so under independence the 40 people
over 60 would include 40 · 90 / 140 = 25.7 card payers. Only 15 of them paid by card,
the largest gap in the table (its cash cell has the same gap, but comes later).

Constraints

  • 1 to 20 rows and 1 to 20 columns; counts are integers between 0 and 10**6; the grand total is positive
  • floats are compared with a tolerance of 1e-6

Goals

  • State independence as P(A and B) = P(A) · P(B) for every cell of a table
  • Compute the count each cell would have under independence
  • Check independence exactly with integer arithmetic
Starting Python…