Grouped Analysis Utilities
Original Python data analyst interviews on grouped support, distinct entities, weighted summaries, tied ranks, categorical comparisons, and constrained reporting totals.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Complete a declared categorical grid and audit unknown rows
Write
declared_grid(groups, categories, rows). Unique string lists declare axes; rows[group,category,integer_count>=0]may name undeclared values. Sum declared cells, including zeros. Return {"cells":[group,category,count]in sorted group/category order,"unknown":input indices outside either axis}. Never create categories from unknown rows. No mutation.2.Reconcile detail cells with two independent marginal totals
Write
rollup_two(rows). Rows[first_key,second_key,amount]use string keys and finite exact decimals, possibly negative. Return{"detail":[a,b,total],"first":[a,total],"second":[b,total],"grand":total}. Sort each list by itskey(s); include observed zero cells. Each row contributes once to each level, never sum subtotal levels together. Empty lists and grand 0 for no rows. No mutation.3.Keep empty, missing-only, and observed-zero groups distinct
Write
observed_groups(groups, rows). groups lists unique strings; rows[known_group,value_or_None]use finite exact decimals. Return[group,row_count,observed_count,sum_or_None,mean_or_None]sorted by group.Nonevalues count as rows but not observed values. With no observed values both numeric summaries areNone, even for a declared empty group. Zero is observed. No mutation.4.Exclude conflicting entity measures before group totals
Write
reconciled_entities(rows). Rows[group,entity,amount]use strings and finite exact decimals. Within each group, an entity with one distinct amount contributes it once; repeated copies add no value. Multiple distinct amounts exclude that entity entirely. Return [group,accepted_entity_count,total,sorted_conflicting_entities] sorted by group; all-conflicting totals are 0. No mutation.5.Share each entity unit across distinct memberships
Write
membership_credit(rows). Rows[entity,group]contain strings and may repeat. Each entity contributes exactly one unit, equally divided among its distinct observed groups. Return[group,total_fractional_credit]sorted by group. Duplicate affiliations receive no extra share; sharing is global per entity across all groups. Empty input returns []. No mutation.6.Join conversion evidence to eligible entity support
Write
eligible_conversion(rows). Rows[group,user,eligible_bool,event_bool]may repeat. Per group, eligible users have eligible=Trueon any row; event users have event=Trueon any row. Converted users are their intersection, even if evidence is on different rows. Return[group,eligible_count,converted_count,rate_or_None]sorted by group; zero eligibility givesNone. No mutation.7.Keep complete-pair change separate from missing endpoints
Write
paired_changes(rows). Rows[group,unique_pair_id,before_or_None,after_or_None]use finite exact decimals. For complete pairs compute after-before. Return[group,complete_count,unsupported_count,mean_change_or_None]sorted by group. A pair missing either endpoint is unsupported; zero endpoints are observed. Do not compare separate marginal means or mutate.8.Separate pooled ratios from equal-row ratio means
Write
grouped_ratios(rows). Rows[group,numerator,denominator]are nonnegative finite exact decimals. Only denominator>0 rows support either statistic. Return [group,supported_count,unsupported_count,pooled_ratio,mean_row_ratio] sorted by group, with both ratiosNoneif no support. pooled=sum(numerator)/sum(denominator)on supported rows;mean_rowaverages their individual ratios. No mutation.9.Compare entity-balanced and observation-weighted means
Write
entity_means(rows). Rows[group,entity,value_or_None]have string keys and finite exact decimals. Within each entity average observed values, then average those means equally across supported entities. Also average all observed rows directly. Return[group,supported_entities,observed_rows,entity_mean,row_mean]sorted by group; both meansNonewithout support. No mutation.10.Merge group moments with between-summary displacement
Write
merge_moments(rows). Rows[group,n,mean,M2]are valid summaries: n integer>=0, M2=sum((x-mean)**2), finite exact decimals; n=0 uses mean=None,M2=0. Return [group,n,mean_or_None,population_variance_or_None,sample_variance_or_None] sorted by group. Include between-summary mean differences; population variance divides M2 by n, sample by n-1 when n>=2. No mutation.11.Find group quantiles from compressed frequency support
Write
frequency_quantile(rows, q). Rows[group,value,integer_frequency>=0], finite exact decimals; 0<=q<=1. Aggregate repeated values. For positive total N, return the smallest positive-frequency value whose cumulative frequency is >=q*N; q=0 returns the minimum supported value. Return[group,quantile_or_None]sorted by group; zero-total groups getNone. Do not expand frequencies or mutate.12.Clip group tails while keeping the original denominator
Write
winsorized_groups(rows, k). Rows[group,value]use finite exact decimals; k>=0 integer. For each sorted group vector x of size n, if 2*k>=n return[group,None,None,None]. Otherwise lower=x[k], upper=x[n-k-1]; clip every value to[lower,upper]and return[group,lower,upper,clipped_mean]. Sort groups. Keep all n observations in the mean, not only the middle ones. No mutation.13.Use midpoint mass for tied group percentile positions
Write
tie_percentiles(rows). Rows[group,unique_id,value_or_None]use finite numbers. Within each group use observed values only, N of them. An observed value v gets (count below v + count equal v / 2)/N. Return[group,id,percentile_or_None]sorted by (group,id); missing values getNoneand do not enter N. This is midpoint CDF mass, not maximum rank/N. No mutation.14.Keep complete score levels and both group rank definitions
Write
ranked_levels(rows, k). Rows[group,unique_id,finite_score]; k>=0 integer. Rank scores descending per group. Dense rank is 1+number of distinct higher scores; competition rank is 1+number of rows with higher scores. Keep all rows with dense rank<=k. Return[group,id,dense,competition]ordered by group, descending score, then id. Ties can yield more than k rows. No mutation.15.Reconcile row contributions to a weighted group mean
Write
contribution_ledger(rows). Rows[group,unique_id,value,weight>=0], finite exact decimals. For group weight W, each row contributes value*weight/W; their sum is the weighted mean. Return [group,W,mean_or_None,[[id,contribution_or_None],...]] sorted by group and id. If W=0 mean and every contribution areNone; zero-weight rows remain listed. No mutation.16.Preserve strict cost-quality frontiers within groups
Write
group_frontiers(rows). Rows[group,unique_id,cost,quality], finite numbers. j dominates i iffcost_j<=cost_iandquality_j>=quality_i, with at least one strict inequality. Return[group,sorted_nondominated_ids]sorted by group. Identical coordinates do not dominate one another; a cheaper but lower-quality point may remain. Compare only within a group. No mutation.17.Bound overlap using only distinct counts and a universe
Write
overlap_bounds(rows). Rows[unique_group,N,A,B]are valid nonnegative integer distinct counts, A,B<=N. Intersection ranges[max(0,A+B-N),min(A,B)]; union=A+B-intersection. Return [group,[min_intersection,max_intersection],[min_union,max_union]] sorted by group. Do not assume independence, disjointness or that A+B is a feasible union. No mutation.18.Apply one supplied segment mixture on supported rates
Write
standardized_rates(weights, rows). weights maps segments to nonnegative exact decimals, sum>0. Rows[group,segment,successes,trials], unique (group,segment), integers 0<=successes<=trials. Normalize weights; average segment rates. Positive-weight absent/zero-trial segments give rateNone. Return[group,rate_or_None,sorted_unsupported_segments]sorted by group. Ignore extras. No mutation.19.Reconcile residual squares into within and mean components
Write
residual_decomposition(rows). Rows[group,residual]use finite exact decimals. Return {"groups":[group,n,mean_residual,RMSE]sorted by group,"within":sum((r-group_mean)**2),"between":sum(n*group_mean**2),"sse":sum(r**2)}. RMSE=sqrt(group squared sum/n). Empty input gives empty groups and zero totals. The decomposition is around zero, not the overall residual mean. No mutation.20.Retain group score ties in threshold precision and recall
Write
threshold_groups(rows, thresholds). Rows[group,score,positive_bool]have finite scores. Select score>=threshold independently at each supplied threshold. Return [group,[[threshold,selected_count,true_positives,precision_or_None,recall_or_None],...]] sorted by group; retain threshold input order/repeats. Precision lacks support if selected=0; recall if group has no positives. No mutation.21.Keep incomplete child totals separate from reconciliation
Write
reconcile_totals(parents, rows, tolerance). parents maps groups to finite exact totals; rows[known_group,child_value_or_None], exact decimals; tolerance>=0. Return[group,observed_sum,missing_count,gap_or_None,status]sorted by group. Any missing child gives gapNone/status"incomplete". Otherwise gap=parent-observed_sum; status"match"iffabs(gap)<=tolerance, else"mismatch". No mutation.22.Measure pairwise overlap on distinct entity memberships
Write
group_overlap(groups, rows). groups lists unique string names; rows[known_group,entity]may repeat. For every pair a<=b in sorted declared groups, return[a,b,intersection_count,union_count,Jaccard_or_None]. Use distinct entity sets; Jaccard=intersection/union,Nonefor empty union. Include self-pairs and declared empty groups. No mutation.23.Union repeated baskets before estimating pair support
Write
basket_pairs(rows). Rows[group,basket_id,item_list]use strings; union repeated (group,basket_id) rows. Empty baskets count in N. For each group, list observed item pairs a<b with positive co-basket count C. Return [group,N,[[a,b,C,C*N/(count_a*count_b)],...]] sorted by group and pair. Each item counts once per basket. A group without observed pairs has an empty pair list. No mutation.24.Compute peer means without treating missing rows as zero
Write
peer_means(rows). Rows[group,unique_id,value_or_None], finite exact decimals. For each row average the observed values of all OTHER rows in its group. A missing current value removes no observation. Return[group,id,peer_observed_count,peer_mean_or_None]sorted by group/id; no peer observations givesNone. Exclude one row, not all rows sharing its value. No mutation.25.Consolidate measures across transitive group links
Write
consolidate_groups(groups, links, rows). Unique string groups; links[known_group,known_group]are undirected and may repeat. Rows[known_group,amount]use finite exact decimals. Form connected components, including isolates. Return[smallest_group,sorted_component_groups,total_amount]sorted by smallest group. A row contributes once even with duplicate links or alternate paths. No mutation.26.Find the most supported contiguous reporting blocks
Write
coarsen_counts(counts, k). counts lists nonnegative integer support by ordered cell; k>=1 integer. Partition ALL cells into nonempty contiguous blocks, each sum>=k. Maximize block count, then lexicographically minimize exclusive block ends. Return{"ends":ends,"totals":block sums},Noneif infeasible; empty counts gives empty lists. Zero cells must belong to a block. No mutation.27.Retain undefined denominator support in observed odds ratios
Write
odds_groups(rows). Rows[group,a,b,c,d]contain nonnegative integer 2x2 counts; sum duplicate group tables cellwise first. Return [group,[a,b,c,d],odds_ratio_or_None] sorted by group. Observed odds ratio is a*d/(b*c); if b*c=0 returnNone, including 0/0. A zero numerator with positive denominator gives 0. No correction, smoothing, significance test or mutation.28.Compute marginal expectations and Pearson discrepancy
Write
contingency_groups(tables). tables maps groups to rectangular nonnegative integer tables with >=1 row/column.Expected[i,j]=row_total[i]*column_total[j]/grand_total. Return[group,expected_matrix,Pearson_sum]sorted by group; both summariesNoneif total=0. Pearson=sum((observed-expected)**2/expected) over positive expected cells; zero-margin cells add 0. No correction, p-value or mutation.29.Summarize category concentration without zero-count logs
Write
effective_categories(rows). Rows[group,category,count>=0 integer]; pool duplicate categories. With positive group total N, p=count/N, H=-sum(p*ln(p)) over positive categories, effective=exp(H). Return[group,N,positive_category_count,H_or_None,effective_or_None]sorted by group. Zero-total groups getNonefor both measures. Zero-count categories contribute no log term. No mutation.30.Round grouped proportions while preserving integer totals
Write
rounded_margins(rows, units). Rows[group,category,integer_count>=0], pooled per category; units maps groups to integer>=0. Quota=count/total*units. Allocate floors, then remaining units by descending fractional remainder, ties category. Return [group,[[category,allocated],...]] sorted by group/category. If total=0 and units>0 useNonefor category list; units=0 assigns zeros. No mutation.