Skip to content

Commit f30e7c6

Browse files
committed
Add set method to LruCache
1 parent 257be0e commit f30e7c6

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

Sprint-2/implement_lru_cache/lru_cache.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,5 +117,32 @@ def get(self,key) ->any:
117117
self.List.remove(node)
118118
self.List.push_head(node=node)
119119
return node.value
120+
def set(self,key,value):
121+
"""
122+
Add a new key-value pair or update an existing key.
123+
Args:
124+
key: Key to insert or update.
125+
value: Value to associate with the key.
126+
Behavior:
127+
- Updates value if key exists and moves node to head.
128+
- Inserts new node at head if key does not exist.
129+
- Evicts least recently used node if cache exceeds limit.
130+
"""
131+
if key in self.map:
132+
node=self.map[key]
133+
node.value=value
134+
self.List.remove(node)
135+
self.List.push_head(node=node)
136+
else:
137+
if self.count>=self.limit:
138+
old_key,old_value=self.List.pop_tail()
139+
del self.map[old_key]
140+
self.count -=1
141+
142+
new_node=self.List.push_head(key=key,value=value)
143+
self.count +=1
144+
self.map[key]=new_node
145+
146+
120147

121148

0 commit comments

Comments
 (0)