Write a python class to implement LRU Cache


Topic: Write a python class to implement LRU Cache

Solution

class DLinkedNode:
    def __init__(self):
        self.key = 0
        self.value = 0
        self.prev = None
        self.next = None
class LRUCache(object):
    def __init__(self, capacity):
        self.capacity = capacity
        self.head = DLinkedNode()
        self.tail = DLinkedNode()
        self.cache = {}
        self.size = 0
        self.head.next = self.tail
        self.tail.prev = self.head
    def add_node(self, node):
        node.next = self.head.next
        node.prev = self.head        
        self.head.next.prev = node
        self.head.next = node
    def remove_node(self, node):
        next = node.next
        prev = node.prev
        prev.next = next
        next.prev = prev
    def move_to_head(self, node ):
        self.remove_node(node)
        self.add_node(node)
    def tail_off(self ):
        res = self.tail.prev
        self.remove_node(res)
        return res       
    def get(self, key):
        node = self.cache.get(key, None)
        if not node:
            return -1
        self.move_to_head(node )
        return node.value
        
    def put(self, key, value):
        node = self.cache.get(key, None)
        if  not node:           
            node = DLinkedNode()
            node.key = key
            node.value = value
            self.cache[key] = node
            self.add_node(node )
            self.size += 1
            if self.size > self.capacity:
                last_node = self.tail_off()
                del self.cache[last_node.key]
                self.size -= 1
        else:
            node.value = value
            self.move_to_head(node )
			



List all Python Programs