Skip to content

Instantly share code, notes, and snippets.

@AntonKueltz
Created February 7, 2019 05:19
Show Gist options
  • Save AntonKueltz/6f049dc355f9e7ede90b6300e1567696 to your computer and use it in GitHub Desktop.
Save AntonKueltz/6f049dc355f9e7ede90b6300e1567696 to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, key, data):
self.next = None
self.prev = None
self.key = key
self.data = data
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __repr__(self):
nodes = []
cur = self.head
while cur:
nodes.append(str(cur.data))
cur = cur.next
return ' -> '.join(nodes)
def insert(self, key, data):
node = Node(key, data)
if not self.head:
self.head = node
self.tail = node
else:
self.head.prev = node
node.next = self.head
self.head = node
def remove(self, node):
prev = node.prev
prev.next = node.next
if node == self.tail:
self.tail = prev
else:
node.next.prev = prev
class LRU:
def __init__(self, cap):
self.hashmap = {}
self.linkedlist = LinkedList()
self.cap = cap
def __repr__(self):
return 'map: {}\tlist: {}'.format({k: v.data for k, v in self.hashmap.items()}, self.linkedlist)
def get(self, key):
if key in self.hashmap:
node = self.hashmap[key]
self.linkedlist.remove(node)
self.linkedlist.insert(node.key, node.data)
return node.data
else:
return -1
def put(self, key, value):
if key in self.hashmap:
node = self.hashmap[key]
self.linkedlist.remove(node)
elif len(self.hashmap) == self.cap:
tail = self.linkedlist.tail
self.linkedlist.remove(tail)
del self.hashmap[tail.key]
self.linkedlist.insert(key, value)
self.hashmap[key] = self.linkedlist.head
print self
if __name__ == '__main__':
cache = LRU(2)
cache.put(1, 1)
cache.put(2, 2)
print cache.get(1)
cache.put(3, 3)
print cache.get(2)
cache.put(4, 4)
print cache.get(1)
print cache.get(3)
print cache.get(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment