LearnCoding

NDCG@k

EasyRanking, Metrics, Search

Problem

relevances lists the graded relevance of items in the order the system ranked them. Compute DCG@k = Σ_{i<k} (2^rel_i − 1)/log2(i + 2) (i is 0-based) and divide by the ideal DCG from the same relevances sorted descending. Return 0.0 if the ideal DCG is 0.

Signature

def ndcg_at_k(relevances: list[int], k: int) -> float: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> close(ndcg_at_k([3, 2, 1, 0], 4), 1.0)
True

>>> close(ndcg_at_k([0, 0, 0], 3), 0.0)
True

Solve it in your own editor; nothing on this page runs code.

Hints

DCG@k = sum of (2^rel_i - 1)/log2(i + 2) for i < k.

The ideal DCG uses the same relevances sorted descending, truncated at k.

Return 0.0 if the ideal DCG is 0 — a zero-division guard.

Reference solution

import math

def ndcg_at_k(relevances, k):
    def dcg(rs):
        return sum((2 ** r - 1) / math.log2(i + 2) for i, r in enumerate(rs[:k]))
    idcg = dcg(sorted(relevances, reverse=True))
    return 0.0 if idcg == 0 else dcg(relevances) / idcg

What a strong solution covers

  • Correct discount indexing.
  • Ideal ordering from all relevances, truncated at k.
  • Zero-division guard.
  • Discusses linear vs exponential gain variants and per-query averaging.

Common mistakes

  • a log2(i) off-by-one
  • computing the ideal DCG only from the top-k of the predicted list.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.