设计一个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
相关推荐
特立独行的猫A7 小时前
我给女儿写了个打字练习:一边敲键盘,一边把小学英语单词记牢
java·后端·python
cpolar技术支持7 小时前
「我这边连不上你那个服务」—— 用清单驱动的 TCP 连通性只读看板,cpolar 让远端同事自己取证
python·内网穿透·tcp·cpolar·网络诊断
云和数据.ChenGuang8 小时前
LangGraph 异步 Node 的设计与写法实践
开发语言·人工智能·python·机器学习·php
天诰9 小时前
SA-K-11 检索会消失吗与四个未解问题
java·服务器·人工智能·python·机器学习·ai编程
benchmark_cc10 小时前
用 QuantDash 读取美股行情:AAPL.US 的运行前检查、排错顺序与数据校验清单
python·数据分析·pandas·量化交易·股票数据·quantdash
羲云网络13 小时前
GPT Image 2.6 接入指南:Flare、Sunburst 怎么选,编辑失败如何排查
人工智能·python·aigc·图像生成·acedatacloud
橙橙笔记17 小时前
具身智能的学习 - 完成一个机械臂 第1节
python·学习·机械臂·具身智能
小小张说故事17 小时前
Python 的 class 语句到底执行了什么?拆开 __prepare__、metaclass.__new__ 和那个被讲反的 __set_name__ 顺序
python
天天被压力19 小时前
【A股分钟级高频数据完全手册 #07】北交所历史分钟K线接口:京市Pro版分时批量
java·人工智能·python
天天被压力19 小时前
【A股分钟级高频数据完全手册 #08】股票日、分时数据接口对比:普通分时与Pro版差异实测
java·人工智能·python