# 实现LRU

```python
'''
方法一
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=5):
        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)
    test.set('b',2)
    test.set('c',3)
    test.set('d',4)
    test.set('e',5)
    # test.set('f',6)
    print (test.get('a'))
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/python/lru.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
