【python】实现LRU缓存

python实现LRU缓存

#coding:utf-8
  
class LRUCache(object):
    """
    """
    def __init__(self, cache_size):
        """
        """
        self.cache_size = cache_size
        self.cache = []

    def put(self, x):
        """
        """
        # 如果已经存在,则将其提至self.cache的最后
        if self.exist(self.cache, x):
            self.cache = self.rerange(self.cache, x)
            return
        else: # 如果不存在,则加入到队列,如果队列已经满了,则清理队首元素,否则不清理
            self.cache.append(x)
            if len(self.cache) > self.cache_size:
                self.cache = self.cache[1:]

    def get(self, x):
        """
        """
        if self.exist(self.cache, x):
            self.cache = self.rerange(self.cache, x)
            return x
        else:
            return None

    def exist(self, cache, x):
        """
        """
        if x in cache:
            return True
        return False

    def rerange(self, cache, x):
        """
        """
        temp = []
        index = cache.index(x)
        for i in range(len(cache)):
            if cache[i] == x:
                continue
            else:
                temp.append(cache[i])
        temp.append(x)
        return temp

if __name__ == "__main__":
    cache = LRUCache(2)

    print('try to put 1 into LRUCache')
    cache.put(1)
    print('try to put 2 into LRUCache')
    cache.put(2)
    print('try to get 1, and the result is %s ' % cache.get(1))
    print('try to put 3 into LRUCache')
    cache.put(3)
    print('try to get 2, and the result is %s ' % cache.get(2))
    print('try to put 4 into LRUCache')

 

你可能感兴趣的:(Python,python学习)