Skip to content

Instantly share code, notes, and snippets.

@balloonio
Last active November 12, 2018 20:41
Show Gist options
  • Save balloonio/0fb8627bf2d88f737b0e6db360852d21 to your computer and use it in GitHub Desktop.
Save balloonio/0fb8627bf2d88f737b0e6db360852d21 to your computer and use it in GitHub Desktop.
A LRU implementation using the above double linked list and a hashmap
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.key2node = {}
self.nodelist = NodeList()
def get(self, key):
if key not in self.key2node:
return -1
node = self.key2node[key]
self.nodelist.remove(node)
self.nodelist.insert(node)
return node.value
def put(self, key, value):
if key in self.key2node:
old_node = self.key2node[key]
self.nodelist.remove(old_node)
new_node = Node(key, value)
self.key2node[key] = new_node
self.nodelist.insert(new_node)
# evict the least used item if cache is over capacity
if self.nodelist.size > self.capacity:
least_used = self.nodelist.tail
self.key2node.pop(least_used.key)
self.nodelist.remove(least_used)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment