Problem using del on dictionary key when the key is obtained through method/object chaining

102 Views Asked by At

I'm working on leetcode 146. Least Recently Used (LRU) cache.

I am using a dictionary as the cache. Integers are the keys and nodes of a doubly linked list are the values.

In short, this segment of code works. If the cache goes over capacity, remove the least recently used node from the list and the cache.

        if len(self.cache) > self.capacity:
          # remove from the list and delete the LRU from cache
          lru = self.left.next # least recently used node
          self.remove(lru) # Remove from linked list
          del self.cache[lru.key] # Delete from dictinary

However if I do not use the lru variable and simply replace it with self.left.next it no longer works.

if len(self.cache) > self.capacity:
      # remove from the list and delete the LRU from cache
      self.remove(self.left.next) # Remove from linked list
      del self.cache[self.left.next.key] # Delete from dictinary

Why is there a problem when not using the lru variable? It seems like the key is not being deleted.

Here is the full code.

class Node:
def __init__(self, key, val):
    self.key = key
    self.val = val
    self.next = None
    self.prev = None

class LRUCache:
def __init__(self, capacity: int):
    self.capacity = capacity
    self.cache = {} # map key to node

    self.left = Node(0, 0)  # Will point to least recently used
    self.right = Node(0, 0)  # Will point to most recently used

    self.left.next = self.right
    self.right.prev = self.left

def insert(self, node):
    prev = self.right.prev
    nxt = self.right
    prev.next = node
    nxt.prev = node
    node.next = nxt
    node.prev = prev

def remove(self, node):
    prev = node.prev
    nxt = node.next
    prev.next = nxt
    nxt.prev = prev

def get(self, key: int) -> int:
    if key in self.cache:
        self.remove(self.cache[key])
        self.insert(self.cache[key])
        return self.cache[key].val
    else:
        return -1

def put(self, key: int, value: int) -> None:
    if key in self.cache:
        self.remove(self.cache[key])
    self.cache[key] = Node(key, value)
    self.insert(self.cache[key])

    if len(self.cache) > self.capacity:
        # remove from the list and delete the LRU from hashmap
        lru = self.left.next
        self.remove(lru)
        del self.cache[lru.key]
        #del self.cache[self.left.next.key]

If you are having trouble following the code. I got it from this youtube video. https://youtu.be/7ABFKPK2hD4

And here is the link to the leetcode problem. https://leetcode.com/problems/lru-cache/

0

There are 0 best solutions below