Score a Top-k Search Result Against Labeled Files
Arrays & HashingAuto-graded · 19 test casesLast updated
Clean a noisy ranked result list (missing, duplicated, unknown, or oversized) and compute precision and recall against ground-truth labels.
A search service is supposed to return the k files it believes are positive matches (for example, photos containing a dog). You have the ground-truth label of every known file and one raw response from the service. The response may be messy, so you must clean it before scoring.
Write a function that returns the precision and recall of the cleaned response.
Inputs
labels: a dictionary mapping each known file ID (string) to a boolean.Truemeans the file is a real positive.returned_ids: the raw response, which is either a list of strings in rank order orNone.k: an integer, the number of results the service was asked to return.
Cleaning the response
Process returned_ids from left to right and build an ordered list accepted:
- If
returned_idsisNone, treat it as an empty list. - For each ID in order, skip it if it is not a key of
labels(unknown ID). Unknown IDs are ignored entirely and never use up one of thekslots. - Skip it if it is already in
accepted(duplicate). Only the first occurrence counts, and later copies never use up a slot. - Otherwise append it to
accepted. - Right after appending, if
k >= 1andlen(accepted) == k, stop processing. Everything after that point is ignored. - If
k <= 0(zero or negative), the cap is disabled: no stop happens, and every known, distinct ID in the response is accepted. Do not treatk <= 0as "accept nothing".
Scoring
Let TP be the number of IDs in accepted whose label is True, and let P be the number of True labels in the whole labels dictionary (including positives that were never returned).
precision = TP / len(accepted). Ifacceptedis empty, precision is0.0.recall = TP / P. IfPis0, recall is0.0.
Return a dictionary with exactly two keys, "precision" and "recall", whose values are the plain (unrounded) floating-point results of those divisions.
Constraints
kis an integer and may be zero or negative (see rule 6).0 <= len(labels) <= 10^50 <= len(returned_ids) <= 10^5when it is notNone- File IDs are strings. Matching is exact and case-sensitive.
- The order of
returned_idsmatters only for deciding which duplicates are dropped and where the cap atkfalls.
Examples
Example 1
Input: score_topk_results({'img1': True, 'img2': False, 'img3': True, 'img4': False}, ['img1', 'img2', 'img3'], 3)
Output: {'precision': 0.6666666666666666, 'recall': 1}
Example 2
Input: score_topk_results({'a': True, 'b': False, 'c': True}, None, 2)
Output: {'precision': 0, 'recall': 0}
Example 3
Input: score_topk_results({'a': True, 'b': False, 'c': True}, ['a', 'a', 'unknown', 'b', 'c'], 3)
Output: {'precision': 0.6666666666666666, 'recall': 1}
Hints
Hint 1
Do the cleaning in one left-to-right pass, keeping a set of IDs you have already accepted.
Hint 2
Unknown IDs and repeated IDs are skipped without consuming one of the k slots, so check them before counting toward k. Only check the cap right after accepting an ID, and only when k >= 1.
Hint 3
Handle the empty cases explicitly: no accepted IDs gives precision 0.0, and no positive labels gives recall 0.0. Recall's denominator counts all positives in labels, not only the returned ones.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Turn the untrusted response into a clean, well-defined list, then score it.
- Replace
Nonewith an empty list. - Walk the response once, keeping a set of IDs already accepted. Accept an ID only if it is a known file and has not been accepted before.
- After each acceptance, stop if the number of accepted IDs equals
k. Because the length starts at 1 after the first acceptance, this check can never fire whenk <= 0, so for zero or negativekthe whole response is processed and no cap applies. Unknown IDs and duplicates never take up a slot. - Count true positives among the accepted IDs by looking up their labels.
- Compute precision as
TP / len(accepted)and recall asTP / P, wherePcounts every positive inlabels. Each falls back to0.0when its denominator is zero.
Why it is correct
After cleaning, accepted contains distinct known IDs (at most k of them when k >= 1), so each is counted exactly once, giving TP <= len(accepted) and TP <= P. Both ratios lie in [0, 1]. Treating None as empty and guarding both denominators avoids any division by zero, and the explicit rule for k <= 0 makes the behaviour defined for every integer k.
Complexity
- Time: O(N + m), where N is the number of labeled files (counting positives) and m is the length of the response. Each set and dictionary operation is O(1) on average.
- Space: O(m) for the seen set and the accepted list.
Reference solution
from typing import Dict, List, Optional
def score_topk_results(labels: Dict[str, bool], returned_ids: Optional[List[str]], k: int) -> Dict[str, float]:
seen = set()
accepted = []
for file_id in returned_ids or []:
if file_id in labels and file_id not in seen:
seen.add(file_id)
accepted.append(file_id)
if len(accepted) == k:
break
tp = sum(1 for file_id in accepted if labels[file_id])
total_pos = sum(1 for is_pos in labels.values() if is_pos)
precision = tp / len(accepted) if accepted else 0.0
recall = tp / total_pos if total_pos else 0.0
return {"precision": precision, "recall": recall}