KatInterview

Score a Top-k Search Result Against Labeled Files

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & Hashinghashingsetsmetrics

Last 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. True means the file is a real positive.
  • returned_ids: the raw response, which is either a list of strings in rank order or None.
  • 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:

  1. If returned_ids is None, treat it as an empty list.
  2. 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 the k slots.
  3. Skip it if it is already in accepted (duplicate). Only the first occurrence counts, and later copies never use up a slot.
  4. Otherwise append it to accepted.
  5. Right after appending, if k >= 1 and len(accepted) == k, stop processing. Everything after that point is ignored.
  6. 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 treat k <= 0 as "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). If accepted is empty, precision is 0.0.
  • recall = TP / P. If P is 0, recall is 0.0.

Return a dictionary with exactly two keys, "precision" and "recall", whose values are the plain (unrounded) floating-point results of those divisions.

Constraints

  • k is an integer and may be zero or negative (see rule 6).
  • 0 <= len(labels) <= 10^5
  • 0 <= len(returned_ids) <= 10^5 when it is not None
  • File IDs are strings. Matching is exact and case-sensitive.
  • The order of returned_ids matters only for deciding which duplicates are dropped and where the cap at k falls.

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.