Metrics ยท Easy
Precision@K
Measure relevant results among the highest-scored k examples.
Task
Implement precision_at_k(labels: list[int], scores: list[float], k: int) -> float. Labels are binary, where 1 means relevant. Sort examples by descending score and return the fraction of relevant labels among the selected examples.
Requirements
- Return 0.0 when k <= 0.
- When k exceeds the dataset size, use every example.
- Preserve original input order when scores tie.
- Inputs have equal length and labels are binary.
Example
labels = [0, 1, 1, 0]
scores = [0.2, 0.9, 0.4, 0.7]
precision_at_k(labels, scores, 2)
# 0.5