设计一个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
相关推荐
liwulin05064 分钟前
【PYTHON】使用Selenium + ChromeDriver以及XPATH语法
开发语言·python·selenium
copyer_xyf6 分钟前
Agentic RAG 实战:PostgreSQL + LangGraph 一条链路
python·postgresql·agent
动力 continue13 分钟前
Python 元类与异常类:类的“制造工厂”与“报错定制师”
开发语言·python·制造
147API21 分钟前
Python批量生成蒸馏数据,并发、重试、幂等和断点续跑
开发语言·jvm·python
青 春 记 忆23 分钟前
零基础入门python04:用注册校验理解字典、集合和条件判断
开发语言·vscode·python·python3.11
kels889927 分钟前
实战排坑:黄金实时API开发,XAUUSD Tick报文异常处理实践
开发语言·python·websocket·网络协议·信息可视化
FBI HackerHarry浩33 分钟前
Pandas 库中用于分类变量独热编码(One-Hot Encoding)的函数 pd.get_dummies() 函数
开发语言·人工智能·python·pandas
高洁0140 分钟前
工信部教考中心证书-人工智能系列本系列
人工智能·python·深度学习·算法
李可以量化1 小时前
Tornado 从入门到精通(二)下:协程调用方式与经典使用模式
python
雪碧透心凉_1 小时前
Python OpenCV图像处理入门
图像处理·python·opencv