当前位置: 首页 > news >正文

设计一个LRU(最近最少使用)缓存

约束和假设

  • 我们正在缓存什么?
    我们正在缓存Web Query的结果
  • 我们可以假设输入是有效的,还是需要对其验证?
    假设输入是有效的
  • 我们可以假设它适应内存吗?

编码实现

class Node(object):def __init__(self, results):self.results = resultsself.prev = Noneself.next = Noneclass LinkedList(object):del __init__(self):self.head = Noneself.tail = Nonedef move_to_front(self, node): # ...def append_to_front(self, node): # ...def remove_from_tail(self): # ...class Cache(obejct):def __init__(self, MAX_SIZE):self.MAX_SIZE = MAX_SIZEself.size = 0self.lookup = {}self.linked_list = LinkedList()def get(self, query)'''Get the stored query result from the cacheAccsssing a node updates its position to the front of the LRU list'''node = self.lookup.get(query)if node is None:return Noneself.linked_list.move_to_front(node)return node.resultsdef set(self, resuts, query):'''Set the results for the given query key in the cache.When updating an entry, updates its position to the front of the LRU listIf the entry is new and the cache is at capacity, remove the oldest entry before the new entry is added '''node = self.lookup.get(query)if node is not None:	node.results = resultsself.linked_list.move_to_front(node)else:if self.size == self.MAX_SIZEself.lookup.pop(self.linked_list.tail.query, None)self.linked_list.remove_from_tail()else:self.size += 1new_node = Node(results)self.linked_list.append_to_front(new_node)self.lookup[query] = new_node
http://www.lryc.cn/news/288725.html

相关文章:

  • shell 循环语句
  • C++(1) 命名空间
  • 【机组】单元模块实验的综合调试与驻机键盘和液晶显示器的使用方式
  • React中实现虚拟加载滚动
  • vue中的Mutations
  • C#用 DateAndTime.DateAdd方法和DateTime.Add(TimeSpan) 方法分别添加一段时间间隔
  • 四、Kotlin 表达式
  • Web开发4:单元测试
  • Ubuntu 16 让ufw防火墙控制docker容器中所有端口
  • <蓝桥杯软件赛>零基础备赛20周--第18周--动态规划初步
  • vb如何获取鼠标形状的特征码
  • chroot: failed to run command ‘/bin/bash’: No such file or directory
  • 蓝桥杯备战——2.矩阵键盘
  • Docker部署思维导图工具SimpleMindMap并实现公网远程访问
  • 机器学习实验2——线性回归求解加州房价问题
  • 宝塔+nextcloud+docker+Onlyoffice 全开启https
  • 呼吸机电机控制主控MCU方案
  • gitlab备份-迁移-升级方案9.2.7升级到15版本最佳实践
  • redis面试题合集-基础
  • (Unity)C# 中的字符串格式化
  • 【项目日记(五)】第二层: 中心缓存的具体实现(上)
  • 使用PSIM软件生成DSP28335流水灯程序
  • 【iOS ARKit】人脸检测追踪基础
  • ES的一些名称和概念总结
  • Javaweb之SpringBootWeb案例之阿里云OSS服务集成的详细解析
  • 【GitHub项目推荐--不错的 Go 学习项目】【转载】
  • 【Git】windows系统安装git教程和配置
  • 办公技巧:PPT制作技巧分享,值得收藏
  • Google Chrome RCE漏洞 CVE-2020-6507 和 CVE-2024-0517 流程分析
  • 前端怎么监听手机键盘是否弹起