PIXELBANKv9.1.0
Menu

Savings from a Semantic Cache

Problem Statement

A semantic cache serves a query from cache when a prior query's similarity exceeds a threshold, saving the cost of an LLM call. Given queries with pairwise similarity to earlier queries, compute total cost saved.

Background

Process queries in order. Query i is a cache hit if any earlier query j < i has similarity[i][j] >= threshold; then it costs nothing and saves cost dollars. Otherwise it is a miss: it costs cost and is added to the cache. The first query is always a miss. Return total dollars saved (num_hits * cost), rounded to 4 decimals.

Your Task

def cache_savings(similarity, threshold, cost):
  • similarity: n x n nested list; similarity[i][j].
  • Return dollars saved.

Input Format

  • similarity (nested list), threshold (float), cost (float).

Output Format

  • A float rounded to 4 decimals.

Sample

sim = [[1,0,0],[0.95,1,0],[0.1,0.2,1]]
print(cache_savings(sim, 0.9, 0.01))

Output:

0.01

Example:

Input:
sim = [[1,0,0],[0.95,1,0],[0.1,0.2,1]]
print(cache_savings(sim, 0.9, 0.01))
Output:
0.01
Reasoning:
  • Query 0 (Index 0): As the first query, there are no prior queries to compare against, so it is a miss. It is added to the cache.
  • Query 1 (Index 1): Compare with Query 0. The similarity is 0.950.95. Since 0.95≥0.90.95 \ge 0.9 (the threshold), this is a hit. No cost is incurred, and the query is not added to the cache.
  • Query 2 (Index 2): Compare with prior queries in the cache (only Query 0 exists). The similarity with Query 0 is 0.10.1. Since 0.1<0.90.1 < 0.9, it is a miss. It costs 0.010.01 and is added to the cache.
  • Calculate Total Savings: There was 1 hit. The savings are calculated as hits×cost=1×0.01=0.01\text{hits} \times \text{cost} = 1 \times 0.01 = 0.01.
  • The final output is 0.01

Constraints:

  • Query i hits if any j<i has similarity[i][j] >= threshold.
  • First query is always a miss; hits save cost each.
  • Round the total to 4 decimals.
🔒

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.