11import time
2+ from collections import OrderedDict
23
34class LruCache :
45 # `LruCache(limit)` should construct
56 # an LRU cache which never stores more than `limit` entries.
67 def __init__ (self , user_limit ):
78 self .limit = user_limit
8- self .our_list = []
9+ self .our_list = OrderedDict ()
910 self .lookup_map = {}
1011
1112 # * `set(key, value)` should associate `value` with the passed `key`.
1213 def set (self , key , value ):
1314
1415 if key in self .lookup_map :
1516 old_item = self .lookup_map [key ]
16- self .our_list .remove (old_item )
17-
17+ self .our_list .pop (key )
1818 wrapped_item = {
1919 "key" : key ,
2020 "value" : value ,
2121 }
2222
2323 #add to list and map
24- self .our_list .insert (0 , wrapped_item )
24+ self .our_list [key ] = wrapped_item
25+ self .our_list .move_to_end (key , last = False )
2526 self .lookup_map [key ] = wrapped_item
2627
2728 #if full remove oldest timestamp so last
2829 if len (self .our_list ) > self .limit :
29- oldest_item = self .our_list .pop ()
30+ # oldest_item = self.our_list.pop()
3031
31- del self .lookup_map [oldest_item ["key" ]]
32-
32+ # del self.lookup_map[oldest_item["key"]]
33+ oldest_key , oldest_item = self .our_list .popitem ()
34+ del self .lookup_map [oldest_key ]
3335
3436 # * `get(key)` should look-up the value previously associated with `key`.
3537 def get (self , key ):
@@ -39,8 +41,9 @@ def get(self, key):
3941 item = self .lookup_map [key ]
4042
4143 #move to front
42- self .our_list .remove (item )
43- self .our_list .insert (0 , item )
44+ # self.our_list.remove(item)
45+ # self.our_list.insert(0, item)
46+ self .our_list .move_to_end (key , last = False )
4447
4548 return item ["value" ]
4649 return None
0 commit comments