-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlruCache.py
33 lines (29 loc) · 885 Bytes
/
lruCache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from doublyLinkedList import DoublyLinkedList
from node import Node
class LruCache():
def __init__(self, itemLimit):
self.itemLimit = itemLimit
self.itemCount = 0
self.store = {}
self.list = DoublyLinkedList()
def set(self, key, val):
if key not in self.store:
self.store[key] = Node(key, val)
self.itemCount += 1
elif self.store.get(key) != val:
self.store[key] = Node(key, val)
self.list.addToHead(self.store.get(key))
if self.itemCount > self.itemLimit:
tail = self.list.removeTail()
del self.store[tail.key]
def get(self, key):
if key in self.store:
node = self.store.get(key)
self.list.moveToHead(node)
return node.val
def remove(self, key):
if key in self.store:
node = self.store.get(key)
self.list.remove(node)
del self.store[node.key]
return node.val