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 postingjob_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 labelcreated_at: posting calendar date formatted asYYYY-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):
-
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 Pythonints (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_atis adatetime.date, blankjob_categoryvalues become"unknown", andresponse_rate = provider_responses / invitations_sent. - Excluded rows keep input order and produce
{"job_id": ..., "reason": ...}. Any repeatedjob_id(even if its earlier occurrence was dropped) receives"duplicate_job_id". Otherwise, assign the first matching rule in this exact order:"not_an_integer"—invitations_sentorprovider_responsescannot be parsed as a finite whole-number integer."negative_count"— either count is strictly negative (< 0)."responses_exceed_invitations"—provider_responses > invitations_sent."zero_invitations"—invitations_sent == 0(treated as missing denominator and excluded)."bad_date"—created_atis missing or not a valid calendarYYYY-MM-DDdate."future_date"—as_ofis provided andcreated_at > as_of(rows withcreated_at == as_ofare valid).
- Strip leading/trailing whitespace on string fields, validate each row in input order, log every excluded or corrupted record via
-
wilson_interval(successes, trials, z=Z_95) -> (low, high):- Compute the two-sided Wilson score confidence interval for
successesout oftrialsbinomial trials (pinninglow = 0.0whensuccesses == 0andhigh = 1.0whensuccesses == trials). RaiseValueErroriftrials <= 0.
- Compute the two-sided Wilson score confidence interval for
-
category_rates(jobs, z=Z_95) -> List[Dict]:- Group cleaned
jobsbyjob_category(sorted alphabetically byjob_category) and return dicts with keys{"job_category", "jobs", "invitations", "responses", "weighted_rate", "ci_low", "ci_high"}, whereweighted_rate = responses / invitationsis the invitation-weighted response rate and(ci_low, ci_high)is its Wilson interval withinvitationsastrials.
- Group cleaned
-
top_categories(rates, k=5) -> List[Dict]:- Return up to
kcategory summary dicts ordered byweighted_ratedescending, breaking ties by higherci_low, and breaking any remaining tie alphabetically byjob_category.
- Return up to
-
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-jobresponse_ratevalues matches it withintol. RaiseValueErrorifjobsis empty or if the difference exceedstol.
- Compute the pooled marketplace rate
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 above2^53), negative numbers, or malformed tokens; Pythonboolvalues are not valid counts. created_atmust represent a real Gregorian calendar date inYYYY-MM-DDformat.- Floating-point comparisons for
check_overall_rateuse tolerancetol = 1e-9by default, andwilson_intervalusesz = 1.959963984540054by default.
Step-by-step walkthrough
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, andcreated_at(YYYY-MM-DD). Our pipeline has five responsibilities:- Compute per-job
response_rate = provider_responses / invitations_sent, treatinginvitations_sent == 0as missing and excluding those rows. - Aggregate an invitation-weighted response rate per
job_categorypaired with a two-sided 95% Wilson score confidence interval. - Return up to
5top categories ordered by weighted response rate, breaking ties by higherci_low(and alphabetically byjob_categoryif still tied). - Log and drop invalid or anomalous rows (
provider_responses > invitations_sent, negative counts, non-integers, duplicatejob_id, or malformed/future dates). - Verify that the invitation-weighted average of per-job rates equals
sum(provider_responses) / sum(invitations_sent)within1e-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_idFrom the
7kept 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.408Because interviews ask for
pandaswhile the test runner uses the Python standard library, each step below shows the vectorizedpandassolution first and then its pure-Python twin insolution.py.- Compute per-job
Clean and log messy rows in pandas
If
pd.read_csvguesses column types automatically, a single"ten"turns an integer column into strings or crashes downstream casts. Read every column asstr(keep_default_na=False), strip whitespace, and coerce explicitly:pd.to_numeric(..., errors="coerce")converts"ten"and""toNaN; checkingnp.isfiniteand% 1 == 0accepts 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"intoNaT(Not-a-Time), andcreated > AS_OFcatches future timestamps.np.selectevaluates validation masks top-to-bottom so every dropped row gets one deterministic reason. Notice the rule priority:resp > invruns beforeinv == 0, soJ203in Example 2 (0invites,1response) 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"]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_countrejectsNoneand booleans (isinstance(True, int)isTruein Python!), tries exactint(stripped)first so integers larger than2^53never lose precision infloat64, and falls back tofloatonly for whole-number strings like"8.0".seen_idsrecords everyjob_idencountered (even if its first row was invalid) so later copies are always marked"duplicate_job_id", matchingdf["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, droppedWhy invitation-weighted average equals total responses divided by total invitations
For job
i, letn_i = invitations_sent(n_i > 0) andk_i = provider_responses, so its job-level response rate isr_i = k_i / n_i. Weighting each job's rate byn_icancels 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
electricaljobs (J101andJ102):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.400000Weighting by invitations answers "what fraction of dispatched invitations receive a professional's reply?" and provides exact binomial counts (
k = sum(k_i)successes out ofn = sum(n_i)trials) for the confidence interval.Compute 95% Wilson score confidence intervals
Why not use the textbook Wald interval
p_hat ± z * sqrt(p_hat * (1 - p_hat) / n)? Whenk = 0out of8invitations (like"unknown"in Example 2), Wald collapses to[0.0, 0.0](falsely claiming0%with zero uncertainty!), and at1out of5it produces[-0.15, 0.55](a negative probability!).The Wilson score interval solves
(p_hat - p)^2 <= z^2 * p * (1 - p) / nfor the true proportionp. That quadratic inequality has a closed form that stays inside[0, 1]and gently pulls small-sample intervals toward0.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
roofingin 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,centerandhalf_widthare mathematically equal ((z^2 / (2n)) / denom), solowis0.0. Infloat64,center - half_widthleaves rounding dust like+3e-17or-1e-17depending onn— which would arbitrarily break ties between two0%categories! Pinninglow = 0.0whensuccesses == 0andhigh = 1.0whensuccesses == trialskeeps 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, highAggregate by category and rank the top 5 with tie-breaking
In
pandas, suminvitations_sentandprovider_responsesperjob_category, compute the vectorized Wilson bounds, and sort byweighted_ratedescending,ci_lowdescending, andjob_categoryascending (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), andflooring(3/5) all haveweighted_rate = 0.600, soci_loworders them0.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]Verify job-level weighted average against pooled totals
In
pandas/NumPy, comparenp.average(jobs_df["response_rate"], weights=jobs_df["invitations_sent"])againstjobs_df["provider_responses"].sum() / jobs_df["invitations_sent"].sum(). Raise an explicitValueErrorrather than usingassert, because running Python with optimization (python -O) stripsassertstatements 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 fromk_iby at most1e-16 * k_i, so any discrepancy exceeding1e-9reliably catches pipeline bugs (such as computingresponse_ratebefore filtering or weighting by the wrong column). On Example 1, both sides equal51 / 125 = 0.408. Here ischeck_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_rateComplete 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:
J108(roofing,0invites,0responses) andJ109(hvac,4invites,6responses):J109is caught asresponses_exceed_invitations(an anomaly logged atWARNING), whileJ108is excluded aszero_invitations(INFO).J101(electrical,5/8 = 0.625) andJ102(electrical,11/32 = 0.34375): pooling gives(5 + 11) / (8 + 32) = 16 / 40 = 0.400(not unweighted0.484375), matching(8 * 0.625 + 32 * 0.34375) / 40 = 0.400within1e-9.roofing(15/25 = 0.600) vsflooring(3/5 = 0.600): both tie at0.600, so their 95% Wilson lower bounds break the tie (0.4074 > 0.2307), ranking the better-evidenced25-invite category ahead of the5-invite category.
Complexity
- Time —
O(n + c log c)fornraw rows andcdistinct categories:clean_jobsscans thenrows once doingO(1)string parsing and hash-set (seen_ids) duplicate checks per row;category_ratesandcheck_overall_rateeach make oneO(n)pass over kept jobs; andcategory_ratesplustop_categoriessort only thecaggregated category dictionaries (O(c log c)). Thepandasversion achieves the sameO(n + c log c)work via vectorized column scans and hash-basedgroupby. - Space —
O(n + c): Storing the cleanedjobslist, thedroppedaudit list, and theseen_idsset usesO(n)memory, while the aggregated category dictionarytotalsusesO(c)memory.
Edge cases
0invitations with0vs> 0responses:0invites and0responses (J108) is a routine exclusion (zero_invitations), whereas0invites and1response (J203in Example 2) is an impossible data corruption (responses_exceed_invitations) becauseresponses > invitationsis checked first.100%response rate (responses == invitations): Kept cleanly (J202in Example 2) withresponse_rate = 1.0andci_high = 1.0(only strictly greater>is dropped).- Formatting quirks, booleans, and huge integers: Whole-number floats like
" 8.0 "parse to8, while"2.5","ten","inf", andTrue/False(sinceboolsubclassesintin Python) are rejected asnot_an_integer. Tryingint(stripped)beforefloatpreserves exact integer precision above2^53. - Impossible, blank, or future dates:
"2025-04-31","2025-13-01", and""fail%Y-%m-%dparsing (bad_date). Dates strictly afteras_ofbecomefuture_date, while jobs created onas_ofare kept. - Duplicate
job_idand blank categories: Every second or later occurrence of ajob_idis dropped asduplicate_job_idregardless of whether the first copy survived. Blank categories become"unknown"sopandas.DataFrame.groupbynever drops their invitations silently. - Exact boundary pinning on
wilson_interval: At0successes, floating-point subtractioncenter - half_widthcan leave±1e-17noise; explicitly pinninglow = 0.0atk = 0andhigh = 1.0atk = nkeeps0%tie-breaking deterministic (job_categoryname breaks the tie). - Fewer than
5categories: Slicingranked[:k]returns all available categories (0to4) without error.
Common mistakes
- Computing
df.groupby("job_category")["response_rate"].mean()instead ofsum(responses) / sum(invitations), which gives small1-invite postings the same weight as50-invite postings. - Dividing
provider_responses / invitations_sentbefore filtering outinvitations_sent == 0and negative/outlier rows, leakinginf,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 below0.0or exceed1.0on 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_rateand calling.head(5)without theci_lowtie-breaker and deterministicjob_categorytie-breaker. - Using
assert abs(job_weighted - pooled) <= 1e-9in production validation code (python -Oskipsassertcompletely; raiseValueErrorinstead).
Alternative approaches
- Rank directly by
ci_low(lower bound of Wilson score) or enforce a minimum invitation floor: Sorting byweighted_ratefirst letsflooring(3 / 5 = 0.600) beatelectrical(16 / 40 = 0.400) even thoughflooringonly has5invitations. Ranking byci_lowdirectly (the classic conservative leaderboard rule) or requiringinvitations >= 30prevents 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 average0.408. - Pure SQL warehouse pipeline: Express the cleaning filters in a
CLEAN_JOBSCTE, group byjob_categorywithSUM(provider_responses) * 1.0 / SUM(invitations_sent), computeci_low/ci_highin a second CTE, andORDER 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>= 30jobs), compute a cluster bootstrap interval instead: resample whole jobs with replacement within each category2,000times, recomputesum(k_i) / sum(n_i)on each resample, and take the2.5thand97.5thpercentiles (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
electricaljobs mostly originate in a supply-constrained region with20%reply rates whileroofingjobs originate in an oversupplied region with65%reply rates, raw category totals confound trade behavior with geography (Simpson's paradox). Apply direct standardization: compute the invitation-weighted response rater_(c, g)inside every(category c, region g)cell, then weight every category across the exact same platform-wide regional invitation weightsw_g(sum_g w_g * r_(c, g)), or estimate marginal effects from a logistic regression controlling forregionand 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_rateandwilson_intervaldepend 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 — deduplicatingjob_idincrementally against a compact key index rather than rescanning historical exports. Wire automated alerts when corruption buckets such asresponses_exceed_invitationsorbad_datebreach a tight ceiling (say> 0.05%of daily rows) so broken upstream instrumentation is caught immediately.
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?
- How would you prevent geographic demand differences from distorting category-to-category response-rate comparisons?
- How would you scale this metric and data-quality audit to an event table ingesting millions of postings per day?
Similar questions
- Python Lists vs. Dicts and Streaming Messy Files
- Time-Zone Weekly Totals and 3-Week Rolling Sums
- Marketplace Provider-Ranking Experiment Design
- Simulating Stay and Switch Win Rates
- Numerically Stable Min, Mean, and Median
- Driving a 72-Hour Executive Rollout Recommendation Across Teams
More Thumbtack interview questions
- Python Lists vs. Dicts and Streaming Messy Files Medium
- Time-Zone Weekly Totals and 3-Week Rolling Sums Medium
- Marketplace Provider-Ranking Experiment Design Hard Pro
- Simulating Stay and Switch Win Rates Medium Pro
- Numerically Stable Min, Mean, and Median Medium Pro
- Driving a 72-Hour Executive Rollout Recommendation Across Teams Hard Pro
- Modeling Adjusted Regional Response-Rate Differences Medium Pro