Neural Mastery
← Practice
Reciprocal Rank Fusionmedium

Reciprocal Rank Fusion

medium RAG & Retrieval 15–20 min

NumPy allowed · plain Python earns 10 bonus points

RAG step 1/4

A query retrieves context

Embedding similarity ranks the documents before generation.
Open lesson →
01query
02embed
03retrieve
04context
What is RAG?→ embed →top context
retrieval.md44%
rag-systems.md33%
agents.md24%

Cosine-like similarity scores ranked before context assembly

Implement Reciprocal Rank Fusion (RRF), the standard technique production hybrid-search systems use to merge a dense vector-search ranking with a sparse BM25/keyword-search ranking into one final ranking.

Task

Implement reciprocal_rank_fusion(rankings, k=60): for every document, sum 1/(k + rank) across every input ranking it appears in (rank is 1-indexed), then return document IDs sorted by descending total score, ties broken by ascending ID.

Function Signature

reciprocal_rank_fusion(rankings: list[list[int]], k: int = 60) -> list[int]

Examples

Example 1: Default k, Overlapping Lists
Input: rankings = [[1, 2, 3], [2, 1, 4]]
Output: [1, 2, 3, 4]
Explanation: Docs 1 and 2 rank highest in both lists
Example 2: Small k, No Overlap (Ties)
Input: rankings = [[1, 2], [3, 4]] k = 1
Output: [1, 3, 2, 4]
Explanation: Rank-1 docs (1 and 3) tie and are ordered by ascending ID

Constraints

  • Libraries (standard library only) are allowed and accepted normally.
  • A plain-Python solution earns 10 bonus points.
  • Rank is 1-indexed: the first element of each ranking list has rank 1.
  • A document missing from a given ranking contributes 0 from that ranking.
  • Ties in total score must be broken by ascending document ID.
  • `k` defaults to 60, the conventional RRF constant from the original paper.
Python3Saved ✓
def reciprocal_rank_fusion(rankings: list[list[int]], k: int = 60) -> list[int]:
"""rankings: a list of ranked result lists (each a list of document
IDs, best-first, 1-indexed rank = position + 1). Return a single
fused ranking (list of document IDs) sorted by descending combined
RRF score = sum over lists containing the doc of 1 / (k + rank).
Ties broken by ascending document ID."""
# Your implementation here
pass

Case 1: Default k, Overlapping Lists
Input: rankings = [[1, 2, 3], [2, 1, 4]]
Expected: [1, 2, 3, 4]
Case 2: Small k, No Overlap (Ties)
Input: rankings = [[1, 2], [3, 4]] k = 1
Expected: [1, 3, 2, 4]