Hybrid Search with Reciprocal Rank Fusion

easy
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 3. Everything before it counts as cleared.

Production RAG systems rarely trust a single retriever. They run keyword search (BM25) and vector search side by side, then merge the ranked lists. The standard way to merge is Reciprocal Rank Fusion:

score(d)=∑r∈rankings1k+rankr(d)\text{score}(d) = \sum_{r \in \text{rankings}} \frac{1}{k + \text{rank}_r(d)}

where rankr(d)\text{rank}_r(d) is the 1-based position of document dd in ranking rr. A document missing from a ranking contributes nothing for that ranking.

Implement rrf(rankings, k=60) that takes a list of rankings (each a list of document ids, best first) and returns a list of (doc_id, score) tuples sorted by score, highest first. Break ties by doc_id alphabetically.

Example

rrf([["a", "b"], ["b", "c"]], k=60)
# [("b", 0.0325...), ("a", 0.0164...), ("c", 0.0161...)]
#rag#retrieval#ranking3 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Hybrid Search with Reciprocal Rank Fusion · TechGradify