File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
Sprint-2/implement_lru_cache Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ from collections import OrderedDict
2+ from typing import Any , Optional
3+ class LruCache :
4+ def __init__ (self , limit : int ):
5+ if limit <= 0 :
6+ raise ValueError ("Limit must be a positive number" )
7+
8+ self ._limit = limit
9+ self .cache = OrderedDict ()
10+
11+ def get (self , key : Any ) -> Optional [Any ]: # lookup the v previously associated with k
12+ if key not in self .cache :
13+ return None
14+
15+ self .cache .move_to_end (key )
16+ return self .cache [key ]
17+
18+ def set (self , key : Any , value : Any ) -> None : # should associate k with passed v
19+ if key in self .cache :
20+ self .cache [key ] = value
21+ self .cache .move_to_end (key )
22+ else :
23+ self .cache [key ] = value
24+ if len (self .cache ) > self ._limit :
25+ self .cache .popitem (last = False )
You can’t perform that action at this time.
0 commit comments