← 返回题库
中级

实现LRU缓存

未完成
中级参考 代码结构已给出,请填写 ____ 处
def solve():
    from pyodide.http import open_url
    from io import StringIO
    cache_log_csv = open_url(____).read()
    import pandas as pd
    from collections import OrderedDict
    from io import StringIO
    cache_log = pd.read_csv(StringIO(____))
    class LRUCache:
        def __init__(____):
            self.capacity = capacity
            self.cache = OrderedDict()
            self.hits = self.misses = self.evictions = ____
        def get(____):
            if key not in self.cache:
                self.misses += ____; return None
            self.cache.move_to_end(____)
            self.hits += ____
            return self.cache[key]
        def set(____):
            if key in self.cache: self.cache.move_to_end(____)
            self.cache[key] = value
            if len(____) > self.capacity:
                self.cache.popitem(____); self.evictions += ____
    lru = LRUCache(____)
    for _, row in cache_log.iterrows():
        key = row['____']
        if row['____'] == '____':
            lru.set(____)
        elif row['____'] == '____':
            lru.get(____)
        elif row['____'] == '____':
            if key in lru.cache: del lru.cache[key]
    total = lru.hits + lru.misses
    print(____)
    print(____)
    print(____)
    print(____)

示例

输入
solve()
期望输出
LRU Cache(capacity=5):
  hits=0, misses=8, evictions=3
  hit_rate=0.0%
  current keys: ['product:4', 'product:8', 'product:3', 'product:9', 'product:5']
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码