• Python实现一个LRU


    class Node:
    	key = None
    	value = None
    	pre = None
    	next = None
    	
    	def __init__(self, key, value):
    		self.key = key
    		self.value = value
    	
    class LRUCache:
    	capacity = 0
    	mapping = {}
    	head = None
    	end = None
    	
    	def __init__(self, capacity):
    		self.capacity = capacity
    
    	def set(self, key, value):
    		if key in self.mapping:
    			oldNode = self.mapping[key]
    			oldNode.value = value
    			self.remove(oldNode)
    			self.set_head(oldNode)
    		else:
    			node = Node(key, value)
    			if len(self.mapping) >= self.capacity:
    				self.mapping.pop(self.end.key)
    				self.remove(self.end)
    				self.set_head(node)
    			else:
    				self.set_head(node)
    			self.mapping[key] = node
    			
    	def set_head(self, n):
    		n.next = self.head
    		n.pre = None
    		if self.head:
    			self.head.pre = n
    		self.head = n
    		if not self.end:
    			self.end = self.head
    			
    	def remove(self, n):
    		if n.pre:
    			n.pre.next = n.next
    		else:
    			self.head = n.next
    		
    		if n.next:
    			n.next.pre = n.pre
    		else:
    			self.end = n.pre
    			
    	def get_all_keys(self):
    		tmp_node = None
    		if self.head:
    			tmp_node = self.head
    			temp = "<{0},{1}>"
    			result = ""
    			while tmp_node:
    				tmp = temp.format(tmp_node.key, tmp_node.value)
    				result += tmp
    				result += " -> "
    				tmp_node = tmp_node.next
    			tmp = temp.format(None, None)
    			result += tmp
    			print(result)
    					
    	def get(self, key):
    		if key in self.mapping:
    			node = self.mapping[key]
    			self.remove(node)
    			self.set_head(node)
    			return node.value
    		else:
    			return -1
    			
    		
    if __name__ == '__main__':
    	cache = LRUCache(100)
    	
    	cache.set('a', '1')
    	cache.set('b', '2')
    	cache.set('c', 3)
    	cache.set('d', 4)
    	
    	cache.get_all_keys()
    	
    	cache.set('a', 5)	
    	cache.get_all_keys()
    	
    	cache.get('c')
    	cache.get_all_keys()
    
  • 相关阅读:
    结构体中的冒号_转
    随机数产生random
    gdb调试段错误及使用
    gcc选项-g与-rdynamic的异同_转
    linux设备模型_转
    boost 1.57.0安装
    技术的正宗与野路子_转
    (转)Java里的堆(heap)栈(stack)和方法区(method)(精华帖,多读读)
    (转)面试大总结之一:Java搞定面试中的链表题目
    (转)类加载器与双亲委派模型
  • 原文地址:https://www.cnblogs.com/leisurelylicht/p/Python-shi-xian-yi-geLRU.html
Copyright © 2020-2023  润新知