Retrieval and Ranking Code
Original AI/ML Engineer coding practice on fusion, ranking metrics, candidate constraints, positional and lexical retrieval, bounded reranking and retrieval identity. Use Python standard-library code without mutating inputs.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Keep each document’s best scored occurrence
Write
unique_topk(rows, k). Rows are[string_id,finite_score]and integer k >= 0. Keep the maximum score for each id, then order by score descending and id alphabetically for ties. Return at most k[id,score]rows. Repeated ids must not consume multiple output slots. Do not mutate rows.2.Filter and deduplicate before taking a cutoff
Write
eligible_ranking(ranked, allowed, k)for string-id lists and integer k >= 0. Scan ranked in order, keeping the first occurrence of each allowed id, and return at most k ids. Disallowed ids and repeated ids use no output slots. The allowed list may repeat ids. Do not truncate ranked before applying these rules.3.Fuse first-occurrence reciprocal ranks
Write
reciprocal_fusion(rankings, c), with string-id ranked lists and integer c >= 0. Each list contributes 1/(c+r) for an id’s first occurrence at its original one-based position r; later duplicates contribute nothing but still occupy positions. Sum contributions across lists. Return[id,score]rows by score descending, then id alphabetically.4.Normalize sources before weighted score fusion
Write
normalized_fusion(sources, weights). Each source has unique[string_id,finite_score]rows; weights are matching nonnegative numbers. Normalize within each source as (score-min)/(max-min), or 1 if all scores are equal. An absent id contributes 0. Return all observed ids with weighted sums, sorted by sum descending then id. Empty sources contribute nothing.5.Compute cutoff AP without duplicate hit credit
Write
average_precision(ranked, relevant, k), with string-id lists and integer k >= 0. Inspect the first k original ranked slots. Credit an id only on its first relevant occurrence; duplicates still occupy slots. Sum precision at credited ranks and divide bymin(k,number of distinct relevant ids). A zero denominator returns 0.0.6.Normalize explicit exponential discounted gain
Write
graded_ndcg(ranked, grades, k). grades maps string ids to integer relevance from 0 to 8. At original ranks r <= k, a first id occurrence earns (2**grade-1)/log2(r+1); duplicates and unknown ids earn 0. Ideal gain sorts all supplied grades descending and uses the same cutoff. Return actual/ideal, or 0.0 if ideal is 0. Integer k >= 0.7.Measure recall within an eligible universe
Write
eligible_recall(ranked, relevant, universe, k)for string-id lists and integer k >= 0. Filter ranked to unique first occurrences in universe, then take k. The target set is distinct relevant ids also in universe. Return the fraction of this target retrieved, orNoneif the target is empty. Ineligible judgments must not inflate the denominator.8.Compare rankings at successive prefix depths
Write
mean_prefix_overlap(a, b, depth), where each ranking contains unique string ids and integer depth >= 0. For d=1..depth, score len(set(a[:d])&set(b[:d]))/d, then return the mean. Short lists are not padded with ids; the denominator remains d. Return 0.0 when depth is zero.9.Aggregate the best distinct chunks per document
Write
document_scores(chunks, m). Entries are[document_id,chunk_id,finite_score], with string ids and positive integer m. For each document/chunk pair keep its maximum score. Average each document’s top m distinct chunk scores, using its actual count if fewer exist. Return[document_id,mean]rows by mean descending then document id.10.Select scored candidates under group caps
Write
capped_ranking(rows, caps, k). Rows are[unique_string_id,group,finite_score]. caps maps group strings to nonnegative integer limits; an absent group has limit 0. Sort by score descending then id, and scan that order, keeping a row only while its group has capacity. Return at most k ids; integer k >= 0. Unfilled slots may remain.11.Interleave sources while skipping seen ids
Write
interleave_rankings(rankings, k), with string-id lists and integer k >= 0. Cycle through sources in input order. On a source’s turn, skip its already-emitted ids and emit its next unseen id, if any. Keep cycling until k ids are emitted or every source is exhausted. Duplicates use no output slots. Return the emitted ids.12.Choose a deterministic marginal-relevance sequence
Write
mmr_order(ids, relevance, similarity, weight, k). ids are unique strings; relevance has matching finite values; similarity is a matching symmetric matrix in[0,1]. Repeatedly choose an unselected i maximizing weight*relevance[i]-(1-weight)*max similarity to selected items; use 0 for the empty maximum. Break ties by id. Return up to k ids; 0<=weight<=1; integer k>=0.13.Page with an exclusive score-and-id cursor
Write
ranking_page(rows, cursor, size). rows have unique[string_id,finite_score]entries. Order by score descending then id. cursor isNoneor[score,id]; keep only rows strictly after that key, even if it is absent. Return {"ids": first size ids,"next": last returned[score,id]if more remain, elseNone}. size is a positive integer.14.Track shared documents’ rank movement
Write
rank_movements(before, after), where rankings contain unique string ids. For every id appearing in both, return[id,old_rank,new_rank,improvement], in after order. Ranks are one-based and improvement =old_rank-new_rank. Ignore ids present in only one ranking; do not compress ranks after finding the intersection.15.Build a case-sensitive positional index
Write
positional_index(documents). documents maps string document ids to lists of token strings. Return a dict token -> dictdocument_id-> ascending zero-based occurrence positions. Keep every repeated-token position, distinguish token case, and omit terms/documents with no occurrence. Empty documents contribute no postings. Do not mutate inputs.16.Find ordered adjacent phrase starts
Write
phrase_starts(index, terms). index maps token -> document -> sorted unique zero-based positions. Return[document,starts]rows for documents containing terms consecutively in the given order, sorted by document id; starts are ascending. Repeated query tokens need distinct consecutive positions. Empty terms or any missing term returns [].17.Rank a corpus with an explicit BM25 formula
Write
bm25_rank(documents, query, k1, b). documents has[unique_id,tokens]rows. Use distinct query terms; N=doc count, L=token count, A=mean L, df=docs containing term, tf=its count. Sum log(1+(N-df+0.5)/(df+0.5))*tf*(k1+1)/(tf+k1*(1-b+b*L/A)) for present query terms. If A=0 scores are 0. Return[id,score]by score descending then id. k1>0; 0<=b<=1.18.Construct raw-count smoothed TF-IDF rows
Write
tfidf_rows(documents), where each document is a list of case-sensitive token strings. For N documents, setidf(term)=1+log((N+1)/(df(term)+1)), using natural log and document frequency. Return one dict per document mapping its present terms to raw occurrence count * idf. Do not normalize vectors. Empty documents give {}; an empty collection gives [].19.Accumulate sparse query-posting dot products
Write
sparse_search(query, postings). query maps terms to finite weights; postings maps terms to unique[document_id,finite_weight]rows. For every document in a query term’s postings, sumquery_weight*document_weightover matching terms. Include touched documents even when their score is 0. Return[id,score]rows by score descending then id. Do not normalize.20.Combine required and excluded posting sets
Write
boolean_candidates(postings, required, excluded, universe). postings maps terms to document-id lists; the other inputs are string lists. Keep universe ids present in every required term’s postings, then remove any in an excluded term’s postings. No required terms means start with the whole universe. A missing required term matches nothing. Return unique ids alphabetically.21.Find the shortest passage covering query terms
Write
covering_window(tokens, query). Inputs are token-string lists. Treat query as a set and find the shortest inclusive[start,end]token-index window containing every query term. Break equal-length ties by earliest start. ReturnNonefor an empty query or when any required term is absent. Repeated query terms do not require repeated occurrences.22.Bound and deduplicate query expansion terms
Write
expand_query(query, expansions, k). query has token strings; expansions maps tokens to[term,nonnegative_weight]rows. Keep unique original terms in first-seen order with weight 1. For expansions of those originals only, ignore original terms and keep each new term’s maximum weight. Append at most k new[term,weight]rows by weight descending then term. Integer k>=0.23.Suppress same-document overlapping candidates
Write
suppress_passages(rows, threshold). Rows are[unique_id,document,start,end,score], with string ids, finite scores and start<end. Sort by score descending then id. Suppress a row if a previously kept row in the same document hasintersection_length/min(lengths)>= threshold. Intervals are half-open; 0<threshold<=1. Return kept ids in selection order.24.Rerank a bounded prefix without changing its tail
Write
rerank_prefix(ranked, scores, window). ranked has unique string ids; scores has[id,finite_score]rows and may repeat ids. In the first window ids, rank scored ids by maximum supplied score descending, ties by original rank; put unscored ids afterward in original order. Ignore scores outside that prefix. Append the untouched tail. Integer window>=0.25.Canonicalize retrieval identity without reordering query
Write
retrieval_key(query, filters, revision). query and revision are strings; filters maps string keys to lists of string values. Return[revision,normalized_query,canonical_filters]. Normalize query by lowercasing and collapsing whitespace, preserving word order. Canonical filters are[key,sorted_unique_values]pairs sorted by key. Keep revision unchanged; retain empty filters.26.Validate candidate embeddings before id deduplication
Write
embedding_ids(rows, model, width), with positive integer width. Each row has string id/model and vector. Accept only matching-model lists of exactly width finite numbers, excluding booleans. Keep the first valid row per id; reject invalid rows and later valid duplicates. Return{"accepted": ids, "rejected": zero-based row indices}, both in input order. Invalid rows must not reserve ids.27.Expand allowed graph candidates by bounded BFS
Write
graph_candidates(edges, starts, allowed, hops). edges maps ids to ordered neighbor lists; other ids are strings and integer hops>=0. Start with unique allowed starts in input order, then breadth-first discover neighbors in their listed order through at most hops edges. Include starts. A disallowed node is neither emitted nor traversed. Return discovery order.28.Allocate a bounded weighted candidate budget
Write
candidate_budget(weights, caps, budget)for matching nonnegative integer lists and integer budget>=0. Start all allocations at 0. For each unit, among positive-weight sources below their caps choose the smallest exact (allocated+1)/weight, ties by lower index; increment it. Stop at budget or when none qualify. Return allocations. Do not round ratios.29.Compare pair order on shared ranked ids
Write
shared_kendall(a, b), where each ranking contains unique string ids. Consider every unordered pair of shared ids. Count concordant pairs whose relative order agrees and discordant pairs whose order reverses. Return (concordant-discordant)/number_of_pairs, orNonewith fewer than two shared ids. Ignore ids outside the intersection without assigning missing ranks.30.Merge touching or overlapping passage intervals
Write
merge_passages(hits), with[document_id,start,end]rows, string ids and integer start<end. Within each document merge overlapping or touching half-open intervals into their union, including transitive chains. Return[document_id,start,end]rows sorted by document id then start. Duplicate or contained intervals must not create extra output or shrink a union.