Skip to content

Commit 825e529

Browse files
committed
lru cache class defining all the logic to check for the cache and evict the LRU least recently used if the limit reaches
1 parent 866b176 commit 825e529

1 file changed

Lines changed: 33 additions & 1 deletion

File tree

‎Sprint-2/implement_lru_cache/lru_cache.py‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,36 @@ def _move_to_head(self, node):
3434
def _pop_tail(self):
3535
node = self.tail.previous
3636
self._remove_node(node)
37-
return node
37+
return node
38+
39+
40+
#Lru class for the logic
41+
class LruCache:
42+
def __init__(self, limit):
43+
if limit <= 0:
44+
raise ValueError("Cache limit must be greater than zero")
45+
self.limit = limit
46+
self.cache = {} #key->Node
47+
self.dll = DoublyLinkedList()
48+
def get(self, key):
49+
node = self.cache.get(key)
50+
if not node:
51+
return None
52+
# Move the node to the head (most recently used)
53+
self.dll._move_to_head(node)
54+
return node.value
55+
def set(self, key, value):
56+
node = self.cache.get(key)
57+
if node:
58+
# Update existing node and move it to head
59+
node.value = value
60+
self.dll._move_to_head(node)
61+
else:
62+
# Create a new node
63+
new_node = Node(key, value)
64+
self.cache[key] = new_node
65+
self.dll._add_to_head(new_node)
66+
if len(self.cache) > self.limit:
67+
# Remove least recently used node
68+
tail = self.dll._pop_tail()
69+
del self.cache[tail.key]

0 commit comments

Comments
 (0)