File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Sprint-2/implement_lru_cache Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ from collections import OrderedDict
2+
3+ class LruCache :
4+ # It keeps the most recently used items.
5+ # If it gets full, it throws away the item we haven't used for the longest time.
6+ def __init__ (self , limit ):
7+ if limit <= 0 :
8+ raise ValueError ("Limit must be positive" )
9+
10+ self .limit = limit
11+ # OrderedDict is like a dictionary. It remembers the order of items.
12+ # It handles the O(1) logic for us automatically.
13+ self .cache = OrderedDict ()
14+
15+ def get (self , key ):
16+ # Trying to find an item
17+ if key not in self .cache :
18+ return None
19+
20+ # If I found it, it means I just "USED" it.
21+ # So I move it to the end (Newest position).
22+ self .cache .move_to_end (key )
23+ return self .cache [key ]
24+
25+ def set (self , key , value ):
26+ # We are adding or updating an item.
27+
28+ if key in self .cache :
29+ # If it exists, update it and move to the end (Newest).
30+ self .cache .move_to_end (key )
31+
32+ self .cache [key ] = value
33+
34+ if len (self .cache ) > self .limit :
35+ # Remove the oldest item.
36+ # last=False means "Remove from the beginning (Oldest)".
37+ self .cache .popitem (last = False )
You can’t perform that action at this time.
0 commit comments