375. Merge several retrievers' rankings with reciprocal rank fusion
Hybrid search often runs a keyword retriever and a vector retriever, then has to merge two rankings whose scores live on different scales. Reciprocal rank fusion ignores the scores and uses only positions.
Write rrf_fuse(rankings, k). rankings is a list of ranked lists of document ids (strings), best first. A document at 1-based rank r in a list gets 1 / (k + r) from that list; a document missing from a list gets nothing from it. Its fused score is the sum over lists.
Return a list of (doc_id, score) tuples, score rounded to 6 decimals, sorted by score descending. Break ties by doc_id ascending.
def rrf_fuse(rankings, k)Example 1
Input: rrf_fuse([["a", "b"], ["b", "c"]], 60)
Output: [("b", 0.032522), ("a", 0.016393), ("c", 0.016129)]
Example 2
Input: rankings = [['d1', 'd2', 'd3'], ['d3', 'd1'], ['d2', 'd4', 'd1']], k = 1
Output: [('d1', 1.083333), ('d2', 0.833333), ('d3', 0.75), ('d4', 0.333333)]
Example 3
Input: rankings = [['x', 'y'], ['y', 'x']], k = 10
Output: [('x', 0.174242), ('y', 0.174242)]
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Use a dict of running sums. enumerate(lst, start=1) gives 1-based ranks.
Hint 2
Sort with key (-score, doc_id).
Common mistakes
- Starting at 0, as the buggy version does, changes every score and divides by zero when k is 0.
Understand the idea
When two retrievers give scores on different scales, you cannot simply add the scores. Reciprocal rank fusion ignores the scores and looks only at positions: a document near the top of a list gets a big share, one further down gets less, and appearing in several lists adds up. The constant k softens the gap between rank 1 and rank 2. Worked example with k = 60: lists ['x', 'y', 'z'] and ['z', 'x']. x: 1 / 61 + 1 / 62 = 0.016393 + 0.016129 = 0.032522. z: 1 / 63 + 1 / 61 = 0.015873 + 0.016393 = 0.032266. y: 1 / 62 = 0.016129. Order: x, z, y.
score(d) = sum over lists containing d of 1 / (k + r), where r is the 1-based rank in that list; documents missing from a list get nothing from it; round to 6 decimals; sort by score descending and break ties by doc id ascending
Starting ranks at 0 shifts every score. RRF is a common default for hybrid keyword plus vector search in RAG pipelines.