FIFO LRU python
时间: 2023-11-08 13:03:41 浏览: 209
FIFO(First-In-First-Out)和LRU(Least Recently Used)都是常用的缓存淘汰算法。它们用于在缓存空间满时确定要被替换的元素。
FIFO算法按照元素进入缓存的顺序进行淘汰。当缓存空间满时,最先进入缓存的元素将被替换掉。
LRU算法根据元素的使用频率进行淘汰。当缓存空间满时,最近最少使用的元素将被替换掉。
下面是使用Python实现FIFO和LRU算法的示例代码:
FIFO算法示例代码:
```python
class FIFO:
def __init__(self, capacity):
self.capacity = capacity
self.cache = []
def get(self, key):
if key in self.cache:
return key
else:
return -1
def put(self, key):
if len(self.cache) >= self.capacity:
self.cache.pop(0)
self.cache.append(key)
```
LRU算法示例代码:
```python
from collections import OrderedDict
class LRU:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key in self.cache:
self.cache.move_to_end(key)
return key
else:
return -1
def put(self, key):
if key in self.cache:
self.cache.move_to_end(key)
elif len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
self.cache[key] = None
```
阅读全文
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)