1. 程式人生 > >python實現LRU

python實現LRU

參考:

https://blog.csdn.net/yz764127031/article/details/79410571

https://blog.csdn.net/hjj414/article/details/38503419

https://www.cnblogs.com/break-python/p/5459169.html

'''
方法一
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'))