美文网首页
lru_cache的简单实现

lru_cache的简单实现

作者: 如烟花非花 | 来源:发表于2016-06-22 10:18 被阅读33次
# -*- encoding=utf-8 -*-
class Node(object):
    def __init__(self, key, val):
        self.prev = None
        self.next = None
        self.key = key
        self.value = val


class DoubleLinkedList(object):
    def __init__(self):
        self.head = None
        self.tail = None

    def _remove(self, node):
        if self.head == self.tail:
            self.head = self.tail = None
            return
        if node == self.head:
            self.head = node.next
            node.next.prev = None
            return
        if node == self.tail:
            self.tail = node.prev
            node.prev.next = None
            return
        node.next.prev = node.prev
        node.prev.next = node.next
        return

    def remove_last_node(self):
        self._remove(self.tail)

    def is_empty(self):
        return self.tail == None

    def add_first(self, node):
        if self.is_empty():
            self.head = self.tail = node
            node.next = node.prev = None
            return
        node.next = self.head
        self.head.prev = node
        node.prev = None
        self.head = node

    def traverse(self):
        if self.is_empty():
            raise ValueError, 'No elem in cache!'
        else:
            cur_node = self.head
            while(cur_node != None):
                print cur_node.value,
                print '\t'
                cur_node = cur_node.next


def max_capacity_check(method_to_decorate):
    def wrapper(self, *args, **kwargs):
        if self.size >= self.capacity:
            print 'Max capacity found and will delete last use node!'
            del self.P[self.cache.tail.key]
            self.cache.remove_last_node()
            self.size -= 1
        method_to_decorate(self, *args, **kwargs)
    return wrapper


class LRUCache(object):
    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity
        self.size = 0
        self.P = dict()
        self.cache = DoubleLinkedList()

    def get(self, key):
        """
        :rtype: int
        """
        if key in self.P.keys() and self.P[key]:
            self.cache._remove(self.P[key])
            self.cache.add_first(self.P[key])
            return self.P[key].value
        else:
            raise ValueError, "No key found in cache"

    @max_capacity_check
    def set(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: nothing
        """
        if key in self.P.keys():
            self.cache._remove(self.P[key])
            self.cache.add_first(self.P[key])
            self.P[key].value = value
        else:
            node = Node(key, value)
            self.P[key] = node
            self.cache.add_first(node)
            self.size += 1


if __name__ == '__main__':
    lru_cache = LRUCache(5)
    for i in range(1, 10):
        lru_cache.set('test%s' % i, i ** 2)

    print lru_cache.P
    lru_cache.cache.traverse()

主要代码出处,轮子就自己不造了,就做一些简单的修改。感谢源代码作者。

相关文章

  • lru_cache的简单实现

    主要代码出处,轮子就自己不造了,就做一些简单的修改。感谢源代码作者。

  • 笔记2——编辑距离 Edit Distance

    lru_cache模块 functools.lru_cache 是装饰器,它实现了备忘(memoization)功...

  • lru_cache装饰器的作用

    python lru_cache装饰器的作用 ru_cache装饰器实现了备忘功能,能够优化函数执行速度,他把耗时...

  • 一个简单的线程安全的LRU_Cache实现

    前言 本文首发于我的公众号:码农手札,主要介绍linux下c++开发的知识包括网络编程的知识同时也会介绍一些有趣的...

  • LRU_Cache

    LRU(Least Recently Used) 表示最近最少使用 LinkedHashMap LRU内部维护的是...

  • python内置缓存lru_cache

    lru_cache LRU算法原理 LRU (Least Recently Used,最近最少使用) 算法是一种缓...

  • 偏函数partial

    Python的内置模块functiontools为解决实际问题提供了便捷的方法,如下所示 其中lru_cache,...

  • 斐波那契数列

    方法一:不导入任何帮助模块计算数列 方法二:导入functools模块下的lru_cache方法计算数列

  • python nonlocal的理解使用

    nonlocal 可以将一个变量声明为非本地变量, 在python的lru_cache看到了使用 实例中, 当a变...

  • 实用装饰器 lru_cache

    python 的functools 提供了许多实用的工具,lru_cache是经常用到的一种。它的作用是缓存该函数...

网友评论

      本文标题:lru_cache的简单实现

      本文链接:https://www.haomeiwen.com/subject/dvagdttx.html