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

约束和假设

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

编码实现

python 复制代码
class Node(object):
	def __init__(self, results):
		self.results = results
		self.prev = None
		self.next = None

class LinkedList(object):
	del __init__(self):
		self.head = None
		self.tail = None
	
	def 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_SIZE
		self.size = 0
		self.lookup = {}
		self.linked_list = LinkedList()

	def get(self, query)
	'''
		Get the stored query result from the cache
		Accsssing a node updates its position to the front of the LRU list
	'''
	node = self.lookup.get(query)
	if node is None:
		return None
	self.linked_list.move_to_front(node)
	return node.results


	def 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 list
		If 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 = results
			self.linked_list.move_to_front(node)
		else:
			if self.size == self.MAX_SIZE
				self.lookup.pop(self.linked_list.tail.query, None)
				self.linked_list.remove_from_tail()
			else:
				self.size += 1
			new_node = Node(results)
			self.linked_list.append_to_front(new_node)
			self.lookup[query] = new_node
相关推荐
言乐621 分钟前
PythonLOLM自动生成复盘报告模型
开发语言·前端·数据库·人工智能·python
水水不水啊26 分钟前
告别切换N个窗口调试:我用 Python + WebView 做了款现代化串口助手(含 TCP/UDP、波形、协议解析)
python·tcp/ip·udp
论文复现现场28 分钟前
DeepSeek V4.1 Flash 各平台价格怎么比?缓存、峰谷计费与 Python 成本计算
开发语言·python·缓存·大模型·成本优化·deepseek
打工仔折腾 AI42 分钟前
鸿蒙平板远控电脑实测:ToDesk蓝牙键鼠、双模式鼠标与跨端剪贴板落地记录
人工智能·后端·python·性能优化·计算机外设·电脑·harmonyos
Metaphor6921 小时前
Python 实用技巧:从零自主生成结构化 PDF 页面
python·pdf
打工仔折腾 AI1 小时前
鸿蒙端ToDesk远控电脑实测:蓝牙键鼠、双模式鼠标与跨端剪贴板实践
后端·python·性能优化·计算机外设·电脑·harmonyos·ai agent 实战
kimnoic1 小时前
Python变量与数据类型全解析(最新整理)
开发语言·python
Python图像识别1 小时前
46-【2027毕设】YOLO11田间杂草检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·qt·课程设计
计算机编程指导师1 小时前
计算机毕设选题:基于Spark+Django的水质多指标关联分析与可视化系统源码 毕业设计 选题推荐 数据分析 机器学习
大数据·hadoop·python·spark·毕业设计·课程设计·水质
小白快快跑哦1 小时前
python-字符串全解(六):正则表达式-分组
python·mysql·正则表达式·分组