lru_cache의 간단한 실현

3191 단어
# -*- 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()


주요 코드의 출처는 바퀴가 스스로 만들지 않고 간단한 수정을 한다.소스 코드 작성자에게 감사 드립니다.

좋은 웹페이지 즐겨찾기