cache icon indicating copy to clipboard operation
cache copied to clipboard

LRU Put() incorrect?

Open ziyueqiu opened this issue 3 years ago • 0 comments

Note that when your PUT is actually an overwrite, you shouldn't do eviction (if self.cn == self.c) or +1 (else).

    def put(self, key, val=1):
        if key not in self.stored:
            n = Node(key, val)
            self.stored[key] = n
            if not self.tail:
                self.tail = n
            self.update_head(n)
        else:
            # Overwrite it correctly
            n = self.stored[key]
            n.val = val
            if n != self.head:
                self.unlink(n)
                self.update_head(n)

        if self.cn == self.c:
            # Evict the tail
            del self.stored[self.tail.key]
            self.tail = self.tail.prev
            self.tail.next = None
        else:
            self.cn += 1

Let me know if I misunderstand your code. Thanks!

ziyueqiu avatar Dec 12 '22 02:12 ziyueqiu