All problems
MediumLoss & Trainingv2026-06-29

Loss & Training ยท Medium

Pairwise Ranking Loss

Implement Pairwise Ranking Loss with production-minded edge case handling.

Task

Implement pairwise_ranking_loss(positive_scores: list[float], negative_scores: list[float], margin: float) -> float. Compute the mean margin-based pairwise ranking loss for aligned positive and negative scores.

Requirements

  • positive_scores and negative_scores have the same shape, and each aligned pair represents one ranking comparison.
  • For each pair, compute max(0, margin - positive_score + negative_score).
  • Return the arithmetic mean of all per-pair losses.
  • Return 0.0 when the inputs are empty.
  • A pair exactly on the margin boundary contributes 0.0.
  • Do not modify the inputs.

Example

positive_scores = [2.0, 1.0, 3.0]
negative_scores = [0.5, 1.5, 1.0]

pairwise_ranking_loss(positive_scores, negative_scores, margin=1.0)
# 0.5
solution.pySign in to save
Public tests run locally in your browser.
Run your code to see public test results.