Workspace/Coding labs
Loading progress

Select current scoped memories under a budget

Intermediate70 min

Implement select_memory(records, tenant, now, budget). Resolve the newest version of each logical key, apply deletion and expiry, then greedily select eligible memories by importance and recency.

Your task

  1. Records contain id, tenant, key, created, expires (integer or None), deleted, importance, and tokens. Fixtures have unique string IDs, string keys, integer times, boolean deleted, nonnegative integer importance, and positive integer token costs.
  2. Budget must be an exact nonnegative integer; raise ValueError otherwise. Only records for the requested tenant and with created <= now participate.
  3. Resolve newest records per logical key using greatest (created, id), including deleted and expired records in version resolution.
  4. After resolution, exclude deleted records and records whose expires is not None and expires <= now. Never restore an older version because a newer one is inactive.
  5. Sort remaining records by descending importance, descending created, then ascending id. Greedily include each record that fits remaining budget, continue past oversized records, and return selected IDs without changing inputs.

Examples

EXAMPLE 1

Inputold style at time 1, corrected style at time 2, corrected value expires at 5; now=5

OutputNo active style memory.

Old versions do not reappear after correction expiry.
solution.pyPython 3.12