Cache Hit Rate
Problem Statement
Given a stream of cache lookups labeled hit or miss, report the hit rate.
Background
Hit rate is hits / total. With no lookups the rate is defined as 0.0.
Your Task
def hit_rate(lookups):
- lookups: list of booleans (True = hit).
- Return the fraction of hits, rounded to 4 decimals.
Input Format
- lookups (list of bool).
Output Format
- A float rounded to 4 decimals.
Sample
print(hit_rate([True, False, True, True]))
Output:
0.75
Example:
print(hit_rate([True, False, True, True]))
0.75
- The input list contains 4 elements, so the total number of lookups is 4.
- We count the hits by identifying the
Truevalues in the list: there are 3 hits (True,True,True). - We calculate the hit rate by dividing the number of hits by the total lookups: 43​=0.75.
- We round the result to 4 decimal places, which remains 0.7500.
- The final output is 0.75
Constraints:
- Rate = hits/total; empty list -> 0.0.
- Round to 4 decimals.
1. Background Knowledge
In high-performance computing and AI agent systems, caching is a fundamental optimization technique. A cache stores frequently accessed data in fast memory (like RAM) to avoid expensive operations like disk I/O or network requests. When a system requests data, it first checks the cache. If the data is present, it is a cache hit; if not, it is a cache miss, and the system must fetch the data from the slower source.
The hit rate is the primary metric for evaluating cache effectiveness. It is defined as the ratio of cache hits to the total number of lookups:
hit_rate=totalhits​A hit rate of 1.0 indicates every lookup was served from the cache, while 0.0 means every lookup required a slow source. In production systems, monitoring this metric helps engineers tune cache size, eviction policies (like LRU or LFU), and data partitioning strategies.
2. Algorithm Approach
This problem follows a counting and aggregation pattern. The approach is straightforward:
- Iterate through the list of lookup results.
- Count the number of hits (where the value is True).
- Calculate the ratio of hits to total lookups.
- Handle edge cases (empty list).
- Round the result to the required precision.
No complex data structures or algorithms are needed. The core logic is a single pass through the input list.
3. Step-by-Step Strategy
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
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.