PIXELBANKv9.1.0
Menu

Recency and Relevance Memory Scoring

Problem Statement

Rank agent memories by a weighted blend of relevance (similarity to the query) and recency (how recently the memory was accessed), returning the top-k memory ids.

Background

A common retrieval score is score = alpha * relevance + (1 - alpha) * recency, where both components are in [0, 1]. Recency is derived from an age: recency = 1 / (1 + age) so newer (smaller age) memories score higher. Ties are broken by smaller id for determinism.

Your Task

Implement:

def rank_memories(memories, alpha, k):
  • memories: list of {"id": int, "relevance": float, "age": float}.
  • Compute score = alpharelevance + (1-alpha)(1/(1+age)).
  • Return the ids of the top k by score (desc), ties broken by smaller id.

Input Format

  • memories (list of dicts), alpha (float in [0,1]), k (int).

Output Format

  • A list of ints (memory ids).

Sample

mem = [{"id":1,"relevance":0.9,"age":10},{"id":2,"relevance":0.4,"age":0}]
print(rank_memories(mem, 0.5, 1))

Output:

[2]

Example:

Input:
mem = [{"id":1,"relevance":0.9,"age":10},{"id":2,"relevance":0.4,"age":0}]
print(rank_memories(mem, 0.5, 1))
Output:
[2]
Reasoning:
  • Calculate the recency component for each memory using the formula recency=11+age\text{recency} = \frac{1}{1 + \text{age}}:
    • For Memory 1 (age 10): 11+10=111≈0.0909\frac{1}{1 + 10} = \frac{1}{11} \approx 0.0909
    • For Memory 2 (age 0): 11+0=1.0\frac{1}{1 + 0} = 1.0
  • Compute the total score for each memory using the weighted blend score=α⋅relevance+(1−α)â‹…recency\text{score} = \alpha \cdot \text{relevance} + (1 - \alpha) \cdot \text{recency} with α=0.5\alpha = 0.5:
    • Memory 1: 0.5â‹…0.9+0.5â‹…0.0909=0.45+0.04545≈0.49550.5 \cdot 0.9 + 0.5 \cdot 0.0909 = 0.45 + 0.04545 \approx 0.4955
    • Memory 2: 0.5â‹…0.4+0.5â‹…1.0=0.2+0.5=0.70.5 \cdot 0.4 + 0.5 \cdot 1.0 = 0.2 + 0.5 = 0.7
  • Rank the memories by score in descending order to determine the top candidates:
    • Memory 2 has a score of 0.70.7
    • Memory 1 has a score of ≈0.4955\approx 0.4955
    • Since 0.7>0.49550.7 > 0.4955, Memory 2 is ranked first.
  • Select the top kk memories where k=1k=1, which corresponds to the single highest-ranked item, Memory 2.
  • The final output is [2]

Constraints:

  • 0 <= alpha <= 1, age >= 0, 0 <= relevance <= 1.
  • recency = 1/(1+age).
  • Sort by score desc, then id asc; return the first k ids.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Recency and Relevance Memory Scoring - Medium | PixelBank