1+ from typing import Any , Hashable
2+
3+ '''
4+ The following implementation of LRU Cache is one of the most elegant pythonic implementations.
5+ It only uses the in-built python dictionary. This works because
6+ the Python dictionary maintains the order of insertion of keys and ensures O(1) operations on insert, delete and access.
7+ '''
8+ class LRUCache (dict ):
9+ '''
10+ Initialize an LRU Cache with given capacity.
11+ capacity : int -> the capacity of the LRU Cache
12+ '''
13+ def __init__ (self , capacity : int ):
14+ self .remaining :int = capacity
15+
16+ '''
17+ This method gets the value associated with the key.
18+ key : Hashable -> a hashable object that is mapped to a value inside of the LRU cache.
19+ returns -> value : Any -> any object that is stored as a value inside of the LRU cache.
20+ '''
21+ def get (self , key :Hashable )-> Any :
22+ if key not in self :
23+ raise KeyError (f"{ key } not found." )
24+ val = self .pop (key ) # Pop the key-value and re-insert to maintain the order
25+ self [key ] = val
26+ return val
27+
28+ '''
29+ This method puts the value associated with the key provided inside of the LRU cache.
30+ key : Hashable -> a hashable object that is mapped to a value inside of the LRU cache.
31+ value: Any -> any object that is to be associated with the key inside of the LRU cache.
32+ '''
33+ def put (self , key :Hashable , value :Any ):
34+ # To pop the last value inside of the LRU cache
35+ if key in self :
36+ self .pop (key )
37+ self [key ] = value
38+ return
39+
40+ if self .remaining > 0 : self .remaining -= 1
41+ # To pop the least recently used item from the dictionary
42+ else : self .pop (next (iter (self )))
43+ self [key ] = value
0 commit comments