zoukankan      html  css  js  c++  java
  • LFU(最近最不常用)实现(python)

    from collections import defaultdict, OrderedDict
    
    
    class Node:
        __slots__ = 'key', 'val', 'cnt'
    
        def __init__(self, key, val, cnt=0):
            self.key, self.val, self.cnt = key, val, cnt
    
    
    class LFUCache:
        def __init__(self, capacity):
            self.capacity = capacity
            self.cache = {}  # type {key: node}
            self.cnt2node = defaultdict(OrderedDict)
            self.mincnt = 0
    
        def get(self, key, default=-1):
            if key not in self.cache:
                return default
    
            node = self.cache[key]
            del self.cnt2node[node.cnt][key]
    
            if not self.cnt2node[node.cnt]:
                del self.cnt2node[node.cnt]
    
            node.cnt += 1
            self.cnt2node[node.cnt][key] = node
    
            if not self.cnt2node[self.mincnt]:
                self.mincnt += 1
            return node.val
    
        def put(self, key, value):
            if key in self.cache:
                self.cache[key].val = value
                self.get(key)
                return
            if len(self.cache) >= self.capacity:
                pop_key, _pop_node = self.cnt2node[self.mincnt].popitem(last=False)
                del self.cache[pop_key]
    
            self.cache[key] = self.cnt2node[1][key] = Node(key, value, 1)
            self.mincnt = 1
    
    
    def test():
        c = LFUCache(2)
        c.put(1, 1)
        c.put(2, 2)
        assert c.get(1) == 1
        c.put(3, 3)
        assert c.get(2) == -1
        assert c.get(3) == 3
        c.put(4, 4)
        assert c.get(1) == -1
        assert c.get(3) == 3
        assert c.get(4) == 4
    
    
    if __name__ == '__main__':
        test()
  • 相关阅读:
    npm 升级所有依赖包
    React中使用 ref 和 findDomNode
    流程控制语句
    Linux 各大目录详解 及 目录颜色详解
    python语言初识(红桃三)
    Linux 虚拟机安装及网络配置
    linux系统介绍
    计算机的五大部件
    Vue生命周期
    Vue实现模糊搜索
  • 原文地址:https://www.cnblogs.com/muzinan110/p/11167071.html
Copyright © 2011-2022 走看看