---
title: NDCG@k
url: https://gurkanozkan.ai/learn/coding/mle-ndcg-k-18/
markdown: https://gurkanozkan.ai/learn/coding/mle-ndcg-k-18.md
kind: coding
difficulty: Easy
topics:
  - Ranking
  - Metrics
  - Search
json: https://gurkanozkan.ai/api/learn/coding/mle-ndcg-k-18.json
robots: noindex
---

# NDCG@k

`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

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

## Examples

Each call and the value it should give.

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

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

## Hints

1. DCG@k = sum of (2^rel_i - 1)/log2(i + 2) for i < k.
2. The ideal DCG uses the same relevances sorted descending, truncated at k.
3. Return 0.0 if the ideal DCG is 0 — a zero-division guard.

## Reference solution

```python
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.*
