美文网首页
LRU缓存淘汰算法python实现

LRU缓存淘汰算法python实现

作者: 钢筋铁骨 | 来源:发表于2020-04-23 23:37 被阅读0次
class LruCache(object):
    def __init__(self, capacity):
        # 线程不安全
        self.capacity = capacity
        self.cache = dict()  # 存缓存内容
        self.keys_order = []  # 存次序,组合起来就是个有序字典

    def show(self):
        print("current cache is: ", self.cache)
        print("current keys_order is: ", self.keys_order)

    def get(self):
        if key in self.cache:
            # 把缓存key放到最前
            self.keys_order.remove(key)
            self.keys_order.append(key)
            return self.cache[key]
        else:
            return None
    # 下面段代码能优化,现在这样写逻辑阅读清晰,但有冗余行
    def set(self, key, value=None):
        # 如果缓存中存在,次序提到最前
        if key in self.cache:
            self.keys_order.remove(key)
            self.keys_order.append(key)
            self.cache[key] = value
        # key不在缓存中,如果缓存已满,删除最旧的缓存数据,增加新数据
        elif len(self.cache) >= self.capacity:
            old_key = self.keys_order.pop(0)
            del self.cache[old_key]
            self.keys_order.append(key)
            self.cache[key] = value
        # key不在缓存中,缓存不满,增加新数据
        else:
            self.keys_order.append(key)
            self.cache[key] = value

相关文章

网友评论

      本文标题:LRU缓存淘汰算法python实现

      本文链接:https://www.haomeiwen.com/subject/yrstwhtx.html