MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / put

Method put

other/lru_cache.py:266–295  ·  view source on GitHub ↗

Sets the value for the input key and updates the Double Linked List

(self, key: T, value: U)

Source from the content-addressed store, hash-verified

264 return None
265
266 def put(self, key: T, value: U) -> None:
267 """
268 Sets the value for the input key and updates the Double Linked List
269 """
270
271 if key not in self.cache:
272 if self.num_keys >= self.capacity:
273 # delete first node (oldest) when over capacity
274 first_node = self.list.head.next
275
276 # guaranteed to have a non-None first node when num_keys > 0
277 # explain to type checker via assertions
278 assert first_node is not None
279 assert first_node.key is not None
280 assert (
281 self.list.remove(first_node) is not None
282 ) # node guaranteed to be in list assert node.key is not None
283
284 del self.cache[first_node.key]
285 self.num_keys -= 1
286 self.cache[key] = DoubleLinkedListNode(key, value)
287 self.list.add(self.cache[key])
288 self.num_keys += 1
289
290 else:
291 # bump node to the end of the list, update value
292 node = self.list.remove(self.cache[key])
293 assert node is not None # node guaranteed to be in list
294 node.val = value
295 self.list.add(node)
296
297 @classmethod
298 def decorator(

Callers 1

Calls 3

removeMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected