Category Response Rates with Invitation Weighting

Medium · Data Manipulation (SQL/Python) · Data Scientist · Onsite

Problem Statement

A services marketplace exports a daily CSV feed where each row represents a customer job posting with six text fields:

  • job_id: string identifier of the posting
  • job_category: trade or service vertical (blank strings map to "unknown")
  • invitations_sent: whole-number count of outreach invites dispatched (>= 0)
  • provider_responses: whole-number count of professionals who replied (>= 0)
  • region: geographic market label
  • created_at: posting calendar date formatted as YYYY-MM-DD

In a pandas workflow — modeled here as five pure-Python functions over csv.DictReader-style row dictionaries — build a data-cleaning and statistical aggregation pipeline (Z_95 = 1.959963984540054 is the two-sided 95% standard normal quantile):

  1. clean_jobs(rows, as_of=None) -> (jobs, dropped):

    • Strip leading/trailing whitespace on string fields, validate each row in input order, log every excluded or corrupted record via logging, and return (jobs, dropped).
    • Valid rows keep input order and produce dicts with keys {"job_id", "job_category", "invitations_sent", "provider_responses", "region", "created_at", "response_rate"}, where counts are Python ints (accepting integer text such as "8" or whole-number floats such as "8.0", while rejecting booleans, fractions like "2.5", and non-numeric strings), created_at is a datetime.date, blank job_category values become "unknown", and response_rate = provider_responses / invitations_sent.
    • Excluded rows keep input order and produce {"job_id": ..., "reason": ...}. Any repeated job_id (even if its earlier occurrence was dropped) receives "duplicate_job_id". Otherwise, assign the first matching rule in this exact order:
      1. "not_an_integer" — invitations_sent or provider_responses cannot be parsed as a finite whole-number integer.
      2. "negative_count" — either count is strictly negative (< 0).
      3. "responses_exceed_invitations" — provider_responses > invitations_sent.
      4. "zero_invitations" — invitations_sent == 0 (treated as missing denominator and excluded).
      5. "bad_date" — created_at is missing or not a valid calendar YYYY-MM-DD date.
      6. "future_date" — as_of is provided and created_at > as_of (rows with created_at == as_of are valid).
  2. wilson_interval(successes, trials, z=Z_95) -> (low, high):

    • Compute the two-sided Wilson score confidence interval for successes out of trials binomial trials (pinning low = 0.0 when successes == 0 and high = 1.0 when successes == trials). Raise ValueError if trials <= 0.
  3. category_rates(jobs, z=Z_95) -> List[Dict]:

    • Group cleaned jobs by job_category (sorted alphabetically by job_category) and return dicts with keys {"job_category", "jobs", "invitations", "responses", "weighted_rate", "ci_low", "ci_high"}, where weighted_rate = responses / invitations is the invitation-weighted response rate and (ci_low, ci_high) is its Wilson interval with invitations as trials.
  4. top_categories(rates, k=5) -> List[Dict]:

    • Return up to k category summary dicts ordered by weighted_rate descending, breaking ties by higher ci_low, and breaking any remaining tie alphabetically by job_category.
  5. check_overall_rate(jobs, tol=1e-9) -> float:

    • Compute the pooled marketplace rate sum(provider_responses) / sum(invitations_sent) and verify that the invitation-weighted average of per-job response_rate values matches it within tol. Raise ValueError if jobs is empty or if the difference exceeds tol.

Examples

Example 1

Input (as_of = date(2025, 6, 30)):

job_id,job_category,invitations_sent,provider_responses,region,created_at
J101,electrical,8,5,north,2025-06-10
J102,electrical,32,11,north,2025-06-11
J103,roofing,25,15,coastal,2025-06-12
J104,hvac,10,6,central,2025-06-13
J105,flooring,5,3,coastal,2025-06-14
J106,carpentry,20,7,central,2025-06-15
J107,masonry,25,4,north,2025-06-16
J108,roofing,0,0,coastal,2025-06-17
J109,hvac,4,6,central,2025-06-18
J110,carpentry,10,-2,north,2025-06-19
J111,masonry,9,3,north,2025-04-31
J112,flooring,ten,2,coastal,2025-06-20
J113,electrical,5,2,north,2025-07-15
J103,roofing,25,15,coastal,2025-06-12

Output:

  • dropped: [{"job_id": "J108", "reason": "zero_invitations"}, {"job_id": "J109", "reason": "responses_exceed_invitations"}, {"job_id": "J110", "reason": "negative_count"}, {"job_id": "J111", "reason": "bad_date"}, {"job_id": "J112", "reason": "not_an_integer"}, {"job_id": "J113", "reason": "future_date"}, {"job_id": "J103", "reason": "duplicate_job_id"}]
  • top_categories(category_rates(jobs), k=5) category order: ["roofing", "hvac", "flooring", "electrical", "carpentry"]
  • check_overall_rate(jobs): 0.408 (51 / 125)

Walk-through: Seven postings (J101–J107) pass validation. electrical pools (5 + 11) / (8 + 32) = 16 / 40 = 0.400 rather than the unweighted job average (0.625 + 0.34375) / 2 = 0.484375. Three categories (roofing 15/25, hvac 6/10, and flooring 3/5) tie at weighted_rate = 0.600; their 95% Wilson lower bounds (0.407395 > 0.312674 > 0.230724) break the tie in favor of larger invitation volume, while masonry (4/25 = 0.160) places 6th and falls outside the top 5.

Example 2

Input (as_of = None):

rows = [
    {"job_id": "J201", "job_category": "  ", "invitations_sent": " 8.0 ",
     "provider_responses": "0", "region": "south", "created_at": "2025-09-01"},
    {"job_id": "J202", "job_category": "glazing", "invitations_sent": "4",
     "provider_responses": "4", "region": "south", "created_at": "2025-09-02"},
    {"job_id": "J203", "job_category": "glazing", "invitations_sent": "0",
     "provider_responses": "1", "region": "south", "created_at": "2025-09-03"},
]

Output:

  • dropped: [{"job_id": "J203", "reason": "responses_exceed_invitations"}]
  • category_rates(jobs) (rounded to 6 decimals):
    • "glazing": jobs=1, invitations=4, responses=4, weighted_rate=1.0, ci_low=0.510109, ci_high=1.0
    • "unknown": jobs=1, invitations=8, responses=0, weighted_rate=0.0, ci_low=0.0, ci_high=0.324408
  • top_categories(category_rates(jobs), k=5) category order: ["glazing", "unknown"]
  • check_overall_rate(jobs): 0.3333333333333333 (4 / 12)

Walk-through: J201 parses " 8.0 " as 8 and maps the blank category to "unknown" with exact ci_low = 0.0. J202 has 4 / 4 = 1.0 with exact ci_high = 1.0. J203 has 1 response on 0 invites, so "responses_exceed_invitations" fires before "zero_invitations". Because only 2 categories exist, top_categories(..., k=5) returns both.

Constraints

  • 0 <= len(rows) <= 10^5
  • Count strings may contain surrounding spaces, whole-number decimals (e.g., "12.0"), arbitrary-precision integers (including values above 2^53), negative numbers, or malformed tokens; Python bool values are not valid counts.
  • created_at must represent a real Gregorian calendar date in YYYY-MM-DD format.
  • Floating-point comparisons for check_overall_rate use tolerance tol = 1e-9 by default, and wilson_interval uses z = 1.959963984540054 by default.

Step-by-step walkthrough

  1. Understand the five goals and trace Sample 1 by hand

    Each row of the input feed describes one marketplace job posting with job_id, job_category, invitations_sent, provider_responses, region, and created_at (YYYY-MM-DD). Our pipeline has five responsibilities:

    1. Compute per-job response_rate = provider_responses / invitations_sent, treating invitations_sent == 0 as missing and excluding those rows.
    2. Aggregate an invitation-weighted response rate per job_category paired with a two-sided 95% Wilson score confidence interval.
    3. Return up to 5 top categories ordered by weighted response rate, breaking ties by higher ci_low (and alphabetically by job_category if still tied).
    4. Log and drop invalid or anomalous rows (provider_responses > invitations_sent, negative counts, non-integers, duplicate job_id, or malformed/future dates).
    5. Verify that the invitation-weighted average of per-job rates equals sum(provider_responses) / sum(invitations_sent) within 1e-9.

    Trace the 14-row Example 1 batch (evaluated at as_of = 2025-06-30) to see every rule in action:

    job_id  category      inv  resp  created_at   Outcome
    J101    electrical      8     5  2025-06-10   KEEP   (rate = 0.62500)
    J102    electrical     32    11  2025-06-11   KEEP   (rate = 0.34375)
    J103    roofing        25    15  2025-06-12   KEEP   (rate = 0.60000)
    J104    hvac           10     6  2025-06-13   KEEP   (rate = 0.60000)
    J105    flooring        5     3  2025-06-14   KEEP   (rate = 0.60000)
    J106    carpentry      20     7  2025-06-15   KEEP   (rate = 0.35000)
    J107    masonry        25     4  2025-06-16   KEEP   (rate = 0.16000)
    J108    roofing         0     0  2025-06-17   DROP: zero_invitations
    J109    hvac            4     6  2025-06-18   DROP: responses_exceed_invitations
    J110    carpentry      10    -2  2025-06-19   DROP: negative_count
    J111    masonry         9     3  2025-04-31   DROP: bad_date (April has 30 days)
    J112    flooring      ten     2  2025-06-20   DROP: not_an_integer
    J113    electrical      5     2  2025-07-15   DROP: future_date (> 2025-06-30)
    J103    roofing        25    15  2025-06-12   DROP: duplicate_job_id
    

    From the 7 kept rows, here is the category summary and top-5 leaderboard:

    Rank  Category     Jobs  Inv  Resp  Weighted Rate   95% Wilson CI
    1     roofing         1   25    15      0.600       [0.4074, 0.7660]  <- 3-way 0.600 tie broken
    2     hvac            1   10     6      0.600       [0.3127, 0.8318]     by higher ci_low!
    3     flooring        1    5     3      0.600       [0.2307, 0.8824]
    4     electrical      2   40    16      0.400       [0.2635, 0.5540]
    5     carpentry       1   20     7      0.350       [0.1812, 0.5671]
    --    masonry         1   25     4      0.160       [0.0640, 0.3465]  (6th, outside top 5)
    
    Overall pooled rate: 51 / 125 = 0.408
    

    Because interviews ask for pandas while the test runner uses the Python standard library, each step below shows the vectorized pandas solution first and then its pure-Python twin in solution.py.

  2. Clean and log messy rows in pandas

    If pd.read_csv guesses column types automatically, a single "ten" turns an integer column into strings or crashes downstream casts. Read every column as str (keep_default_na=False), strip whitespace, and coerce explicitly:

    • pd.to_numeric(..., errors="coerce") converts "ten" and "" to NaN; checking np.isfinite and % 1 == 0 accepts whole-number exports like "8.0" while rejecting "2.5" and "inf".
    • pd.to_datetime(..., format="%Y-%m-%d", errors="coerce") turns nonexistent calendar dates like "2025-04-31" into NaT (Not-a-Time), and created > AS_OF catches future timestamps.
    • np.select evaluates validation masks top-to-bottom so every dropped row gets one deterministic reason. Notice the rule priority: resp > inv runs before inv == 0, so J203 in Example 2 (0 invites, 1 response) is logged as a data corruption (responses_exceed_invitations) rather than a routine zero-invitation exclusion.
    import logging
    import numpy as np
    import pandas as pd
    
    log = logging.getLogger("response_rates")
    AS_OF = pd.Timestamp("2025-06-30")
    
    df = pd.read_csv("jobs.csv", dtype=str, keep_default_na=False)
    for col in df.columns:
        df[col] = df[col].str.strip()
    
    inv = pd.to_numeric(df["invitations_sent"], errors="coerce")
    resp = pd.to_numeric(df["provider_responses"], errors="coerce")
    created = pd.to_datetime(df["created_at"], format="%Y-%m-%d", errors="coerce")
    
    inv_int = np.isfinite(inv) & (inv % 1 == 0)
    resp_int = np.isfinite(resp) & (resp % 1 == 0)
    
    rules = [
        ("duplicate_job_id", df["job_id"].duplicated()),
        ("not_an_integer", ~inv_int | ~resp_int),
        ("negative_count", (inv < 0) | (resp < 0)),
        ("responses_exceed_invitations", resp > inv),
        ("zero_invitations", inv == 0),
        ("bad_date", created.isna()),
        ("future_date", created > AS_OF),
    ]
    conditions = [cond for _, cond in rules]
    reasons = [name for name, _ in rules]
    df["drop_reason"] = np.select(conditions, reasons, default="")
    
    dropped_df = df[df["drop_reason"] != ""]
    for reason, count in dropped_df["drop_reason"].value_counts().items():
        log.warning("dropping %d rows: %s", count, reason)
    
    keep = df["drop_reason"] == ""
    jobs_df = df[keep].copy()
    jobs_df["invitations_sent"] = inv[keep].astype("int64")
    jobs_df["provider_responses"] = resp[keep].astype("int64")
    jobs_df["created_at"] = created[keep]
    # pandas groupby drops NaN keys by default; map empty categories to "unknown".
    jobs_df["job_category"] = jobs_df["job_category"].replace("", "unknown")
    jobs_df["response_rate"] = jobs_df["provider_responses"] / jobs_df["invitations_sent"]
    
  3. Write the plain-Python cleaning twin: clean_jobs

    In pure Python, we apply the exact same validation pipeline one row dictionary at a time:

    • parse_count rejects None and booleans (isinstance(True, int) is True in Python!), tries exact int(stripped) first so integers larger than 2^53 never lose precision in float64, and falls back to float only for whole-number strings like "8.0".
    • seen_ids records every job_id encountered (even if its first row was invalid) so later copies are always marked "duplicate_job_id", matching df["job_id"].duplicated().
    from typing import Dict, List, Optional, Tuple
    import logging
    import math
    from datetime import date, datetime
    
    LOG = logging.getLogger(__name__)
    
    
    def parse_count(raw_value) -> Optional[int]:
        """Parse an integer count from text such as '12', ' 12 ', or '12.0'; return None if invalid."""
        if raw_value is None or isinstance(raw_value, bool):
            return None
        if isinstance(raw_value, int):
            return raw_value
        if isinstance(raw_value, str):
            stripped = raw_value.strip()
            if not stripped:
                return None
            try:
                return int(stripped)
            except ValueError:
                pass
        try:
            number = float(raw_value)
        except (ValueError, TypeError, OverflowError):
            return None
        if not math.isfinite(number) or not number.is_integer():
            return None
        return int(number)
    
    
    def parse_date(raw_value) -> Optional[date]:
        """Parse a real calendar date in YYYY-MM-DD form, or return None ('2024-02-30', '', 'soon')."""
        if raw_value is None:
            return None
        if isinstance(raw_value, date) and not isinstance(raw_value, datetime):
            return raw_value
        if not isinstance(raw_value, str):
            return None
        try:
            return datetime.strptime(raw_value.strip(), "%Y-%m-%d").date()
        except ValueError:
            return None
    
    
    def drop_reason(
        invitations: Optional[int],
        responses: Optional[int],
        created: Optional[date],
        as_of: Optional[date],
    ) -> Optional[str]:
        if invitations is None or responses is None:
            return "not_an_integer"
        if invitations < 0 or responses < 0:
            return "negative_count"
        if responses > invitations:
            return "responses_exceed_invitations"
        if invitations == 0:
            return "zero_invitations"
        if created is None:
            return "bad_date"
        if as_of is not None and created > as_of:
            return "future_date"
        return None
    
    
    def clean_jobs(
        rows: List[Dict[str, str]],
        as_of: Optional[date] = None,
    ) -> Tuple[List[Dict], List[Dict]]:
        jobs: List[Dict] = []
        dropped: List[Dict] = []
        seen_ids = set()
    
        for row in rows:
            job_id = (row.get("job_id") or "").strip()
            invitations = parse_count(row.get("invitations_sent"))
            responses = parse_count(row.get("provider_responses"))
            created = parse_date(row.get("created_at"))
    
            if job_id in seen_ids:
                reason = "duplicate_job_id"
            else:
                reason = drop_reason(invitations, responses, created, as_of)
            seen_ids.add(job_id)
    
            if reason is not None:
                if reason == "zero_invitations":
                    LOG.info("excluding job %s: %s", job_id, reason)
                else:
                    LOG.warning("dropping job %s: %s", job_id, reason)
                dropped.append({"job_id": job_id, "reason": reason})
                continue
    
            category_text = (row.get("job_category") or "").strip()
            category = category_text if category_text else "unknown"
            region = (row.get("region") or "").strip()
    
            jobs.append({
                "job_id": job_id,
                "job_category": category,
                "invitations_sent": invitations,
                "provider_responses": responses,
                "region": region,
                "created_at": created,
                "response_rate": responses / invitations,
            })
    
        return jobs, dropped
    
  4. Why invitation-weighted average equals total responses divided by total invitations

    For job i, let n_i = invitations_sent (n_i > 0) and k_i = provider_responses, so its job-level response rate is r_i = k_i / n_i. Weighting each job's rate by n_i cancels the per-job denominators cleanly:

    weighted_rate = sum(n_i * r_i) / sum(n_i)
                  = sum(n_i * (k_i / n_i)) / sum(n_i)
                  = sum(k_i) / sum(n_i)
    

    That identity means the invitation-weighted average is simply the pooled proportion (total responses divided by total invitations). Compare that against a naive unweighted mean on our two electrical jobs (J101 and J102):

    J101:   5 responses /  8 invitations = 0.62500
    J102:  11 responses / 32 invitations = 0.34375
    
    Unweighted mean of job rates = (0.62500 + 0.34375) / 2               = 0.484375  (treats 8 invites == 32 invites!)
    Invitation-weighted rate     = (8 * 0.62500 + 32 * 0.34375) / 40     = 16 / 40 = 0.400000
    

    Weighting by invitations answers "what fraction of dispatched invitations receive a professional's reply?" and provides exact binomial counts (k = sum(k_i) successes out of n = sum(n_i) trials) for the confidence interval.

  5. Compute 95% Wilson score confidence intervals

    Why not use the textbook Wald interval p_hat ± z * sqrt(p_hat * (1 - p_hat) / n)? When k = 0 out of 8 invitations (like "unknown" in Example 2), Wald collapses to [0.0, 0.0] (falsely claiming 0% with zero uncertainty!), and at 1 out of 5 it produces [-0.15, 0.55] (a negative probability!).

    The Wilson score interval solves (p_hat - p)^2 <= z^2 * p * (1 - p) / n for the true proportion p. That quadratic inequality has a closed form that stays inside [0, 1] and gently pulls small-sample intervals toward 0.5:

    p_hat      = k / n
    denom      = 1 + z^2 / n
    center     = (p_hat + z^2 / (2 * n)) / denom
    half_width = (z / denom) * sqrt(p_hat * (1 - p_hat) / n + z^2 / (4 * n^2))
    CI         = [center - half_width, center + half_width]   (z = 1.959964 for 95%)
    

    Verify roofing in Example 1 (k = 15, n = 25, p_hat = 0.60):

    z^2 = 3.841459,   z^2 / 25 = 0.153658,   denom = 1.153658
    center     = (0.60 + 0.076829) / 1.153658 = 0.586681   (pulled slightly toward 0.50!)
    half_width = (1.959964 / 1.153658) * sqrt(0.24 / 25 + 3.841459 / 2500)
               = 1.698912 * sqrt(0.011137) = 0.179286
    95% CI     = [0.407395, 0.765967]
    

    One crucial floating-point detail: at k = 0, center and half_width are mathematically equal ((z^2 / (2n)) / denom), so low is 0.0. In float64, center - half_width leaves rounding dust like +3e-17 or -1e-17 depending on n — which would arbitrarily break ties between two 0% categories! Pinning low = 0.0 when successes == 0 and high = 1.0 when successes == trials keeps boundaries exact.

    from typing import Tuple
    import math
    
    Z_95 = 1.959963984540054
    
    
    def wilson_interval(successes: int, trials: int, z: float = Z_95) -> Tuple[float, float]:
        if trials <= 0:
            raise ValueError("the Wilson interval needs at least one trial")
    
        p_hat = successes / trials
        z2 = z * z
        denom = 1.0 + z2 / trials
        center = (p_hat + z2 / (2.0 * trials)) / denom
        spread = math.sqrt(p_hat * (1.0 - p_hat) / trials + z2 / (4.0 * trials * trials))
        half_width = (z / denom) * spread
    
        low = center - half_width
        high = center + half_width
    
        if successes == 0:
            low = 0.0
        if successes == trials:
            high = 1.0
        return low, high
    
  6. Aggregate by category and rank the top 5 with tie-breaking

    In pandas, sum invitations_sent and provider_responses per job_category, compute the vectorized Wilson bounds, and sort by weighted_rate descending, ci_low descending, and job_category ascending (so any remaining exact tie is deterministic):

    import numpy as np
    
    Z_95 = 1.959963984540054
    
    by_cat = (
        jobs_df.groupby("job_category", as_index=False)
        .agg(
            jobs=("job_id", "size"),
            invitations=("invitations_sent", "sum"),
            responses=("provider_responses", "sum"),
        )
        .sort_values("job_category")
    )
    by_cat["weighted_rate"] = by_cat["responses"] / by_cat["invitations"]
    
    n = by_cat["invitations"]
    p_hat = by_cat["weighted_rate"]
    z2 = Z_95 ** 2
    denom = 1.0 + z2 / n
    center = (p_hat + z2 / (2.0 * n)) / denom
    half_width = (Z_95 / denom) * np.sqrt(p_hat * (1.0 - p_hat) / n + z2 / (4.0 * n ** 2))
    by_cat["ci_low"] = (center - half_width).where(by_cat["responses"] > 0, 0.0)
    by_cat["ci_high"] = (center + half_width).where(by_cat["responses"] < n, 1.0)
    
    top5_df = by_cat.sort_values(
        by=["weighted_rate", "ci_low", "job_category"],
        ascending=[False, False, True],
    ).head(5)
    

    Watch how the tie-breaker works on Example 1's three 60% categories: roofing (15/25), hvac (6/10), and flooring (3/5) all have weighted_rate = 0.600, so ci_low orders them 0.4074 > 0.3127 > 0.2307 — rewarding the category backed by stronger sample evidence! Here is the pure-Python twin:

    from typing import Dict, List, Tuple
    
    
    def category_rates(jobs: List[Dict], z: float = Z_95) -> List[Dict]:
        totals: Dict[str, Dict[str, int]] = {}
        for job in jobs:
            category = job["job_category"]
            if category not in totals:
                totals[category] = {"jobs": 0, "invitations": 0, "responses": 0}
            totals[category]["jobs"] += 1
            totals[category]["invitations"] += job["invitations_sent"]
            totals[category]["responses"] += job["provider_responses"]
    
        result: List[Dict] = []
        for category in sorted(totals):
            cat_totals = totals[category]
            invitations = cat_totals["invitations"]
            responses = cat_totals["responses"]
            weighted_rate = responses / invitations
            low, high = wilson_interval(responses, invitations, z)
            result.append({
                "job_category": category,
                "jobs": cat_totals["jobs"],
                "invitations": invitations,
                "responses": responses,
                "weighted_rate": weighted_rate,
                "ci_low": low,
                "ci_high": high,
            })
        return result
    
    
    def rank_key(rate_row: Dict) -> Tuple[float, float, str]:
        return (-rate_row["weighted_rate"], -rate_row["ci_low"], rate_row["job_category"])
    
    
    def top_categories(rates: List[Dict], k: int = 5) -> List[Dict]:
        ranked = sorted(rates, key=rank_key)
        return ranked[:k]
    
  7. Verify job-level weighted average against pooled totals

    In pandas / NumPy, compare np.average(jobs_df["response_rate"], weights=jobs_df["invitations_sent"]) against jobs_df["provider_responses"].sum() / jobs_df["invitations_sent"].sum(). Raise an explicit ValueError rather than using assert, because running Python with optimization (python -O) strips assert statements completely:

    job_weighted_avg = float(np.average(jobs_df["response_rate"], weights=jobs_df["invitations_sent"]))
    pooled_rate = float(jobs_df["provider_responses"].sum() / jobs_df["invitations_sent"].sum())
    if abs(job_weighted_avg - pooled_rate) > 1e-9:
        raise ValueError(f"Mismatch: {job_weighted_avg} vs {pooled_rate}")
    

    In floating-point arithmetic, n_i * (k_i / n_i) differs from k_i by at most 1e-16 * k_i, so any discrepancy exceeding 1e-9 reliably catches pipeline bugs (such as computing response_rate before filtering or weighting by the wrong column). On Example 1, both sides equal 51 / 125 = 0.408. Here is check_overall_rate:

    from typing import Dict, List
    
    
    def check_overall_rate(jobs: List[Dict], tol: float = 1e-9) -> float:
        if not jobs:
            raise ValueError("no jobs to check")
    
        weighted_rate_sum = 0.0
        total_invitations = 0
        total_responses = 0
        for job in jobs:
            weighted_rate_sum += job["invitations_sent"] * job["response_rate"]
            total_invitations += job["invitations_sent"]
            total_responses += job["provider_responses"]
    
        job_weighted_avg = weighted_rate_sum / total_invitations
        pooled_rate = total_responses / total_invitations
    
        if abs(job_weighted_avg - pooled_rate) > tol:
            raise ValueError(f"weighted mean of job rates {job_weighted_avg} != pooled rate {pooled_rate}")
        return pooled_rate
    
  8. Complete solution

    Putting all pure-Python twin functions together into solution.py:

    from typing import Dict, List, Optional, Tuple
    import logging
    import math
    from datetime import date, datetime
    
    # The sandbox has no pandas, so each function below is the plain-Python twin of one pandas step.
    # Rows come in as csv.DictReader gives them: a dict of text values per job posting.
    
    LOG = logging.getLogger(__name__)
    
    # Two-sided 95% standard normal quantile (Phi^-1(0.975)).
    Z_95 = 1.959963984540054
    
    
    def parse_count(raw_value) -> Optional[int]:
        """Parse an integer count from text such as '12', ' 12 ', or '12.0'; return None if invalid."""
        # Reject missing values and booleans (bool subclasses int in Python, so float(True) == 1.0).
        if raw_value is None or isinstance(raw_value, bool):
            return None
        if isinstance(raw_value, int):
            return raw_value
        if isinstance(raw_value, str):
            stripped = raw_value.strip()
            if not stripped:
                return None
            # Try exact integer parsing first so integers above 2**53 never lose precision in float64.
            try:
                return int(stripped)
            except ValueError:
                pass
        # Fall back to float64 for whole-number exports like '12.0'.
        try:
            number = float(raw_value)
        except (ValueError, TypeError, OverflowError):
            return None
        if not math.isfinite(number) or not number.is_integer():
            return None
        return int(number)
    
    
    def parse_date(raw_value) -> Optional[date]:
        """Parse a real calendar date in YYYY-MM-DD form, or return None ('2024-02-30', '', 'soon')."""
        if raw_value is None:
            return None
        if isinstance(raw_value, date) and not isinstance(raw_value, datetime):
            return raw_value
        if not isinstance(raw_value, str):
            return None
        try:
            return datetime.strptime(raw_value.strip(), "%Y-%m-%d").date()
        except ValueError:
            return None
    
    
    def drop_reason(
        invitations: Optional[int],
        responses: Optional[int],
        created: Optional[date],
        as_of: Optional[date],
    ) -> Optional[str]:
        """Return why a non-duplicate row is excluded, or None to keep it (first matching rule wins)."""
        if invitations is None or responses is None:
            return "not_an_integer"
        if invitations < 0 or responses < 0:
            return "negative_count"
        # Check responses > invitations BEFORE invitations == 0 so 2 responses to 0 invites is flagged
        # as an impossible outlier rather than a benign zero-invitation exclusion.
        if responses > invitations:
            return "responses_exceed_invitations"
        if invitations == 0:
            return "zero_invitations"
        if created is None:
            return "bad_date"
        # A job created on `as_of` itself is valid; only strictly later dates (> as_of) are in the future.
        if as_of is not None and created > as_of:
            return "future_date"
        return None
    
    
    def clean_jobs(
        rows: List[Dict[str, str]],
        as_of: Optional[date] = None,
    ) -> Tuple[List[Dict], List[Dict]]:
        """Validate raw rows; return (jobs, dropped), both in input order.
    
        jobs item shape: {"job_id", "job_category", "invitations_sent", "provider_responses",
                          "region", "created_at", "response_rate"}
        dropped item shape: {"job_id", "reason"}
        """
        jobs: List[Dict] = []
        dropped: List[Dict] = []
        # seen_ids: set of job_id strings seen so far (mirrors pandas Series.duplicated()).
        seen_ids = set()
    
        for row in rows:
            job_id = (row.get("job_id") or "").strip()
            invitations = parse_count(row.get("invitations_sent"))
            responses = parse_count(row.get("provider_responses"))
            created = parse_date(row.get("created_at"))
    
            if job_id in seen_ids:
                reason = "duplicate_job_id"
            else:
                reason = drop_reason(invitations, responses, created, as_of)
            # Record job_id even if the first copy was dropped, matching pandas duplicated(keep="first").
            seen_ids.add(job_id)
    
            if reason is not None:
                if reason == "zero_invitations":
                    LOG.info("excluding job %s: %s", job_id, reason)
                else:
                    LOG.warning("dropping job %s: %s", job_id, reason)
                dropped.append({"job_id": job_id, "reason": reason})
                continue
    
            # Map blank categories to "unknown" because pandas groupby silently drops NaN keys.
            category_text = (row.get("job_category") or "").strip()
            category = category_text if category_text else "unknown"
            region = (row.get("region") or "").strip()
    
            jobs.append({
                "job_id": job_id,
                "job_category": category,
                "invitations_sent": invitations,
                "provider_responses": responses,
                "region": region,
                "created_at": created,
                "response_rate": responses / invitations,
            })
    
        return jobs, dropped
    
    
    def wilson_interval(successes: int, trials: int, z: float = Z_95) -> Tuple[float, float]:
        """Wilson score interval (low, high) for a binomial proportion. Raises ValueError if trials <= 0."""
        if trials <= 0:
            raise ValueError("the Wilson interval needs at least one trial")
    
        p_hat = successes / trials
        z2 = z * z
        denom = 1.0 + z2 / trials
        center = (p_hat + z2 / (2.0 * trials)) / denom
        spread = math.sqrt(p_hat * (1.0 - p_hat) / trials + z2 / (4.0 * trials * trials))
        half_width = (z / denom) * spread
    
        low = center - half_width
        high = center + half_width
    
        # Pin exact boundary roots: at 0 successes low is 0.0 and at all successes high is 1.0.
        # Without pinning, float cancellation leaves ~1e-17 noise that corrupts ci_low tie-breaks.
        if successes == 0:
            low = 0.0
        if successes == trials:
            high = 1.0
        return low, high
    
    
    def category_rates(jobs: List[Dict], z: float = Z_95) -> List[Dict]:
        """Return one summary dict per job_category, sorted alphabetically by job_category."""
        # totals maps category -> {"jobs": int, "invitations": int, "responses": int}.
        totals: Dict[str, Dict[str, int]] = {}
        for job in jobs:
            category = job["job_category"]
            if category not in totals:
                totals[category] = {"jobs": 0, "invitations": 0, "responses": 0}
            totals[category]["jobs"] += 1
            totals[category]["invitations"] += job["invitations_sent"]
            totals[category]["responses"] += job["provider_responses"]
    
        result: List[Dict] = []
        for category in sorted(totals):
            cat_totals = totals[category]
            invitations = cat_totals["invitations"]
            responses = cat_totals["responses"]
            # Invitation-weighted job rate sum(n_i * (k_i / n_i)) / sum(n_i) simplifies to sum(k_i) / sum(n_i).
            weighted_rate = responses / invitations
            low, high = wilson_interval(responses, invitations, z)
            result.append({
                "job_category": category,
                "jobs": cat_totals["jobs"],
                "invitations": invitations,
                "responses": responses,
                "weighted_rate": weighted_rate,
                "ci_low": low,
                "ci_high": high,
            })
        return result
    
    
    def rank_key(rate_row: Dict) -> Tuple[float, float, str]:
        # Negate numeric keys so sorted() ranks highest weighted_rate first, then highest ci_low,
        # and breaks any remaining tie alphabetically by job_category.
        return (-rate_row["weighted_rate"], -rate_row["ci_low"], rate_row["job_category"])
    
    
    def top_categories(rates: List[Dict], k: int = 5) -> List[Dict]:
        """Return the top k rows of category_rates by weighted_rate, breaking ties by higher ci_low."""
        ranked = sorted(rates, key=rank_key)
        return ranked[:k]
    
    
    def check_overall_rate(jobs: List[Dict], tol: float = 1e-9) -> float:
        """Return the pooled rate sum(responses) / sum(invitations) over all jobs.
    
        Raises ValueError if the invitation-weighted mean of job-level response_rate differs
        from the pooled rate by more than tol, or if jobs is empty.
        """
        if not jobs:
            raise ValueError("no jobs to check")
    
        weighted_rate_sum = 0.0
        total_invitations = 0
        total_responses = 0
        for job in jobs:
            weighted_rate_sum += job["invitations_sent"] * job["response_rate"]
            total_invitations += job["invitations_sent"]
            total_responses += job["provider_responses"]
    
        job_weighted_avg = weighted_rate_sum / total_invitations
        pooled_rate = total_responses / total_invitations
    
        # Raise ValueError instead of assert because `python -O` disables assert statements.
        if abs(job_weighted_avg - pooled_rate) > tol:
            raise ValueError(f"weighted mean of job rates {job_weighted_avg} != pooled rate {pooled_rate}")
        return pooled_rate
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of computing marketplace response rates like calculating a baseball team's batting average: a hitter who went 5 for 8 (62.5%) and a teammate who went 11 for 32 (34.4%) do not give the team a 48.4% batting average — together they collected 16 hits in 40 at-bats (40.0%). Weighting each job's response rate k_i / n_i by its invitations n_i cancels the denominators so the category rate equals the pooled proportion sum(responses) / sum(invitations), and pairing that pooled proportion with a Wilson score interval (a binomial confidence interval obtained by inverting the score test so bounds stay strictly inside [0, 1] even on tiny samples) quantifies how much statistical uncertainty remains.

A naive pipeline that runs df.groupby("job_category")["response_rate"].mean() treats a 1-invite job identically to a 100-invite job, produces inf/NaN on 0-invite postings, silently drops blank categories, and breaks ties arbitrarily. Worse, using the textbook Wald interval p_hat ± 1.96 * sqrt(p_hat * (1 - p_hat) / n) collapses to [0, 0] at 0 responses and dips below 0 on small categories.

Trace four rows from Example 1 (as_of = 2025-06-30) to see every piece fit together:

  1. J108 (roofing, 0 invites, 0 responses) and J109 (hvac, 4 invites, 6 responses): J109 is caught as responses_exceed_invitations (an anomaly logged at WARNING), while J108 is excluded as zero_invitations (INFO).
  2. J101 (electrical, 5/8 = 0.625) and J102 (electrical, 11/32 = 0.34375): pooling gives (5 + 11) / (8 + 32) = 16 / 40 = 0.400 (not unweighted 0.484375), matching (8 * 0.625 + 32 * 0.34375) / 40 = 0.400 within 1e-9.
  3. roofing (15/25 = 0.600) vs flooring (3/5 = 0.600): both tie at 0.600, so their 95% Wilson lower bounds break the tie (0.4074 > 0.2307), ranking the better-evidenced 25-invite category ahead of the 5-invite category.

Complexity

  • Time — O(n + c log c) for n raw rows and c distinct categories: clean_jobs scans the n rows once doing O(1) string parsing and hash-set (seen_ids) duplicate checks per row; category_rates and check_overall_rate each make one O(n) pass over kept jobs; and category_rates plus top_categories sort only the c aggregated category dictionaries (O(c log c)). The pandas version achieves the same O(n + c log c) work via vectorized column scans and hash-based groupby.
  • Space — O(n + c): Storing the cleaned jobs list, the dropped audit list, and the seen_ids set uses O(n) memory, while the aggregated category dictionary totals uses O(c) memory.

Edge cases

  • 0 invitations with 0 vs > 0 responses: 0 invites and 0 responses (J108) is a routine exclusion (zero_invitations), whereas 0 invites and 1 response (J203 in Example 2) is an impossible data corruption (responses_exceed_invitations) because responses > invitations is checked first.
  • 100% response rate (responses == invitations): Kept cleanly (J202 in Example 2) with response_rate = 1.0 and ci_high = 1.0 (only strictly greater > is dropped).
  • Formatting quirks, booleans, and huge integers: Whole-number floats like " 8.0 " parse to 8, while "2.5", "ten", "inf", and True/False (since bool subclasses int in Python) are rejected as not_an_integer. Trying int(stripped) before float preserves exact integer precision above 2^53.
  • Impossible, blank, or future dates: "2025-04-31", "2025-13-01", and "" fail %Y-%m-%d parsing (bad_date). Dates strictly after as_of become future_date, while jobs created on as_of are kept.
  • Duplicate job_id and blank categories: Every second or later occurrence of a job_id is dropped as duplicate_job_id regardless of whether the first copy survived. Blank categories become "unknown" so pandas.DataFrame.groupby never drops their invitations silently.
  • Exact boundary pinning on wilson_interval: At 0 successes, floating-point subtraction center - half_width can leave ±1e-17 noise; explicitly pinning low = 0.0 at k = 0 and high = 1.0 at k = n keeps 0% tie-breaking deterministic (job_category name breaks the tie).
  • Fewer than 5 categories: Slicing ranked[:k] returns all available categories (0 to 4) without error.

Common mistakes

  • Computing df.groupby("job_category")["response_rate"].mean() instead of sum(responses) / sum(invitations), which gives small 1-invite postings the same weight as 50-invite postings.
  • Dividing provider_responses / invitations_sent before filtering out invitations_sent == 0 and negative/outlier rows, leaking inf, NaN, or corrupted counts into category totals.
  • Using the textbook Wald formula p_hat ± 1.96 * sqrt(p_hat * (1 - p_hat) / n), which produces [0, 0] at zero responses and can dip below 0.0 or exceed 1.0 on small samples.
  • Coercing bad cells with errors="coerce" and silently .dropna()-ing them without logging per-reason drop counts, hiding upstream logging breakages.
  • Sorting only by weighted_rate and calling .head(5) without the ci_low tie-breaker and deterministic job_category tie-breaker.
  • Using assert abs(job_weighted - pooled) <= 1e-9 in production validation code (python -O skips assert completely; raise ValueError instead).

Alternative approaches

  • Rank directly by ci_low (lower bound of Wilson score) or enforce a minimum invitation floor: Sorting by weighted_rate first lets flooring (3 / 5 = 0.600) beat electrical (16 / 40 = 0.400) even though flooring only has 5 invitations. Ranking by ci_low directly (the classic conservative leaderboard rule) or requiring invitations >= 30 prevents tiny-sample luck from dominating rankings.
  • Empirical Bayes shrinkage: Fit a Beta(alpha, beta) prior across categories and rank by the posterior mean (responses + alpha) / (invitations + alpha + beta), smoothly pulling low-volume categories toward the marketplace average 0.408.
  • Pure SQL warehouse pipeline: Express the cleaning filters in a CLEAN_JOBS CTE, group by job_category with SUM(provider_responses) * 1.0 / SUM(invitations_sent), compute ci_low / ci_high in a second CTE, and ORDER BY weighted_rate DESC, ci_low DESC, job_category ASC LIMIT 5.

Follow-up questions

  • When multiple outreach invites belong to the same job posting, why can the standard binomial Wilson interval be overconfident, and how would you fix it? Invitations dispatched for the same posting share that customer's budget, project clarity, and urgency, creating positive within-job correlation (clustering) that makes the raw count n = sum(invitations) overstate the effective sample size and makes a plain binomial Wilson interval too narrow. Once a category has enough postings (for instance >= 30 jobs), compute a cluster bootstrap interval instead: resample whole jobs with replacement within each category 2,000 times, recompute sum(k_i) / sum(n_i) on each resample, and take the 2.5th and 97.5th percentiles (or fit a Beta-Binomial / cluster-robust logistic model).
  • How would you prevent geographic demand differences from distorting category-to-category response-rate comparisons? If electrical jobs mostly originate in a supply-constrained region with 20% reply rates while roofing jobs originate in an oversupplied region with 65% reply rates, raw category totals confound trade behavior with geography (Simpson's paradox). Apply direct standardization: compute the invitation-weighted response rate r_(c, g) inside every (category c, region g) cell, then weight every category across the exact same platform-wide regional invitation weights w_g (sum_g w_g * r_(c, g)), or estimate marginal effects from a logistic regression controlling for region and posting week.
  • How would you scale this metric and data-quality audit to an event table ingesting millions of postings per day? Because both weighted_rate and wilson_interval depend only on the additive totals (jobs, sum_invitations, sum_responses) per (job_category, date), maintain a daily partitioned rollup table alongside a daily (date, drop_reason, row_count) audit table — deduplicating job_id incrementally against a compact key index rather than rescanning historical exports. Wire automated alerts when corruption buckets such as responses_exceed_invitations or bad_date breach a tight ceiling (say > 0.05% of daily rows) so broken upstream instrumentation is caught immediately.

Follow-up questions

Similar questions

More Thumbtack interview questions

All 8 Thumbtack questions →