Grading Top-K Picks With Precision and Recall

Recommender SystemsEasy+10 XP+10

Grading Top-K Picks With Precision and Recall

Nobody scrolls past the first handful of recommendations, so recommender systems are judged on the top k and nothing else.

  • Precision@k — of the k items you showed, what fraction were relevant?
  • Recall@k — of all the relevant items that exist, what fraction did you show?

Task: write precision_recall_at_k(recommended, relevant, k) returning [precision, recall], both rounded to 4 decimal places.

  • recommended is ordered best-first; only its first k entries count.
  • If the list is shorter than k, use what's there — precision divides by how many you actually showed.
  • Return 0.0 for either metric when its denominator would be zero.
  • relevant is a set of items, unordered.

The two pull against each other. Recommending everything makes recall perfect and precision worthless; recommending one sure thing does the reverse. Fixing k is what forces the system to commit.

Examples

recommended = [1, 2, 3, 4, 5]
relevant = [2, 4, 6]
k = 3
returns [0.3333, 0.3333]
recommended = [9, 8, 7]
relevant = [1, 2]
k = 3
returns [0.0, 0.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run