【python刷题】LRU
什么是LRU? |
LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。该算法赋予每个页面一个访问字段,用来记录一个页面自上次被访问以来所经历的时间 t,当须淘汰一个页面时,选择现有页面中其 t 值最大的,即最近最少使用的页面予以淘汰。
我们需要记住以下几点就行了:这里以队列为例
- 要设置一个容量,比如我们设置队列的长度为2;
- 当进来一个元素,比如('a',1),插入到列表中[('a',1)],再进来一个('b',2),插入到列表中,[('a',1),('b',2)],再进来一个('c',3),此时列表已满,这时我们要将最久未被使用的元素删除,也就是('a','1'),再将新元素插入到列表中,[('b',2),('c',3)];
- 假设这时我们使用了('b','2'),那么当前元素就是我们最近使用过的了,队列就变为[('c',3),('b',2)],下次再添加一个新的元素的时候就是优先将('c','3')移除了;
- 我们要保证删除和插入的时间复杂度为O(1),因此要使用字典,而且字典中的元素要是有序的,因此使用python自带的OrderedDict;
- 进一步的是,假设我们要自己实现底层,那么使用的结果就是hash双向链表,这样查找、删除、插入的时间复杂度就都是O(1);
方法一:列表模拟 |
class LRUCache:
#@param capacity,an integer
def __init__(self,capacity):
self.cache ={}
self.used_list=[]
self.capacity = capacity
#@return an integer
def get(self,key):
if key in self.cache:
#使用一个list来记录访问的顺序,最先访问的放在list的前面,最后访问的放在list的后面,故cache已满时,则删除list[0],然后插入新项;
if key != self.used_list[-1]:
self.used_list.remove(key)
self.used_list.append(key)
return self.cache[key]
else:
return -1
def set(self,key,value):
if key in self.cache:
self.used_list.remove(key)
elif len(self.cache) == self.capacity:
self.cache.pop(self.used_list.pop(0))
self.used_list.append(key)
self.cache[key] = value
方法二:有序字典模拟 |
import collections
# 基于orderedDict实现
class LRUCache(collections.OrderedDict):
'''
function:利用collection.OrdereDict数据类型实现最近最少使用的算法
OrdereDict有个特殊的方法popitem(Last=False)时则实现队列,弹出最先插入的元素
而当Last=True则实现堆栈方法,弹出的是最近插入的那个元素。
实现了两个方法:get(key)取出键中对应的值,若没有返回None
set(key,value)更具LRU特性添加元素
'''
def __init__(self, size=2):
self.size = size
self.cache = collections.OrderedDict() # 有序字典
def get(self, key):
if key in self.cache.keys():
# 因为在访问的同时还要记录访问的次数(顺序)
value = self.cache.pop(key)
# 保证最近访问的永远在list的最后面
self.cache[key] = value
return value
else:
value = None
return value
def set(self, key, value):
if key in self.cache.keys():
self.cache.pop(key)
self.cache[key] = value
elif self.size == len(self.cache):
self.cache.popitem(last=False)
self.cache[key] = value
else:
self.cache[key] = value
测试小例子:
if __name__ == '__main__':
test = LRUCache()
test.set('a', 1)
print(test.cache)
test.set('b', 2)
print(test.cache)
test.set('c', 3)
print(test.cache)
test.set('d', 4)
print(test.cache)
test.set('e', 5)
print(test.cache)
# test.set('f',6)
t1 = test.get('d')
print(t1)
print(test.cache)
结果:
OrderedDict([('a', 1)])
OrderedDict([('a', 1), ('b', 2)])
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
OrderedDict([('b', 2), ('c', 3), ('d', 4)])
OrderedDict([('c', 3), ('d', 4), ('e', 5)])
4
OrderedDict([('c', 3), ('e', 5), ('d', 4)])
方法三:hash双向链表 |
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
self.prev = None
class DoubleList:
def __init__(self):
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.size = 0
self.head.next = self.tail
self.tail.prev = self.head
def addLast(self, x):
x.prev = self.tail.prev
x.next = self.tail
self.tail.prev.next = x
self.tail.prev = x
self.size += 1
def remove(self, x):
x.prev.next = x.next
x.next.prev = x.prev
self.size -= 1
def removeFirst(self):
if self.head.next == self.tail:
return None
first = self.head.next
self.remove(first)
return first
def getSize(self):
return self.size
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.cache = DoubleList()
self.dic = {}
def makeRecently(self, key):
x = self.dic.get(key)
self.cache.remove(x)
self.cache.addLast(x)
def addRecently(self, key, val):
x = Node(key, val)
self.cache.addLast(x)
self.dic[key] = x
def deleteKey(self, key):
x = self.dic.get(key)
self.cache.remove(x)
self.dic.pop(key)
def removeLeastRecently(self):
deleteNode = self.cache.removeFirst()
deleteKey = deleteNode.key
self.dic.pop(deleteKey)
def get(self, key):
if not key in self.dic:
return -1
self.makeRecently(key)
return self.dic.get(key)
def put(self, key ,val):
if key in self.dic:
self.deleteKey(key)
self.addRecently(key, val)
return
if self.cap == self.cache.size:
self.removeLeastRecently()
self.addRecently(key, val)
这种实现还有点问题,只要掌握思路就好了。
参考:
百度百科
https://blog.csdn.net/qq_35810838/article/details/83035759
labuladong的算法小抄
【python刷题】LRU的更多相关文章
- Python 刷题笔记
Python 刷题笔记 本文记录了我在使用python刷题的时候遇到的知识点. 目录 Python 刷题笔记 选择.填空题 基本输入输出 sys.stdin 与input 运行脚本时传入参数 Pyth ...
- python刷题第二周
1: 第3章-5 字符转换 (15 分) 本题要求提取一个字符串中的所有数字字符('0'--'9'),将其转换为一个整数输出. 输入格式: 输入在一行中给出一个不超过80个字符且以回车结束的字符串. ...
- python刷题第四周
本周有所收获的题目: 第一题: 第4章-17 水仙花数(20 分) (20 分) 水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身. 例如:153=1×1×1+5×5×5 ...
- python刷题第三周
以下是本周有所收获的题目 第一题: 第4章-4 验证"哥德巴赫猜想" (20 分) 数学领域著名的"哥德巴赫猜想"的大致意思是:任何一个大于2的偶数总能表示为两 ...
- python刷题专用函数。。
无它,非bin()莫属. bin(x) Convert an integer number to a binary string. The result is a valid Python expre ...
- python 刷题必备
1.判断输入的数字是否是回文数: 学习内容:把数字转成字符串 1. def is_palindrome(n): n=str(n) m=n[::-1] return n==m 2. tmp_str = ...
- Python 刷题知识点
if : elif : else : print('{0} \n{1} \n{2}' .format((a + b), (a - b), (a * b))) print(*[num**2 for nu ...
- python部落刷题宝学到的内置函数(二)
感觉到刷题宝有一个好处,也许也不是好处,它的答案必须是真正输出的值,也就是说应该输出字符串aaaa的时候,答案必须写成界面上返回的值,即'aaaa'.有利于真正记忆返回值类型,但是....太繁琐了 1 ...
- python部落刷题宝学到的内置函数
最近加入了python部落,感觉里面的刷题宝很有意思,玩了一下,知道了许多以前并不清楚的内置函数,然后感觉到快要记不住了,所以开始陈列一下 1.divmod(a,b):取a除以b的商和余数,功效等价于 ...
随机推荐
- C# 7-zip 压缩和解压缩
using System; using System.Collections.Generic; using System.Text; using SevenZip; using System.IO; ...
- jsp页面技术总结
1.日期框只能选择不能输入属性设置 data-options="editable:false" 2.列表中多出一列空白 .datagrid-view1{ width: 0px!im ...
- MongoDb学习(四)--Repository----语法关键字
表7.查询方法支持的关键字 关键词 样品 逻辑结果 After findByBirthdateAfter(Date date) {"birthdate" : {"$gt& ...
- ES6中class的使用+继承
一.Class 介绍+基本语法(1).介绍通过class关键字,可以定义类.基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的 ...
- SparkSql自定义数据源之读取的实现
一.sparksql读取数据源的过程 1.spark目前支持读取jdbc,hive,text,orc等类型的数据,如果要想支持hbase或者其他数据源,就必须自定义 2.读取过程 (1)sparksq ...
- 数据库的查询(结合YGGL.sql)
(如有错误,欢迎指正!) 1.select 语句查询 (1)查询employees表员工部门号和性别,要求消除重复行. mysql> select distinct 员工部门号,性别 from ...
- 风炫安全WEB安全学习第二十二节课 DOM型XSS讲解
风炫安全WEB安全学习第二十二节课 DOM型XSS讲解 Dom型XSS演示 通过Javascript,可以重构整个HTML文档,你可以添加.移除.改变或重排页面上的项目 要改变页面的某个东西,Java ...
- 阿里云centos7[linux]安装nginx
标题 说明 服务器版本 Centos7 x64 nginx版本 1.19.6 作者 walton 一.准备 创建安装包目录并进入 mkdir /usr/dev/nginx cd /usr/dev/ng ...
- Solon rpc 之 SocketD 协议 - 单链接双向RPC模式
Solon rpc 之 SocketD 协议系列 Solon rpc 之 SocketD 协议 - 概述 Solon rpc 之 SocketD 协议 - 消息上报模式 Solon rpc 之 Soc ...
- log4net配置及使用
log4net简介 log4net库是Apache log4j框架在Microsoft.NET平台的实现,是一个帮助程序员将日志信息输出到各种目标(控制台.文件.数据库等)的工具. log4net详解 ...