File tree Expand file tree Collapse file tree 2 files changed +75
-0
lines changed
Sprint-2/implement_lru_cache Expand file tree Collapse file tree 2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change 1+ class LruCache :
2+ def __init__ (self , limit ):
3+ if limit <= 0 :
4+ raise ValueError ("Limit must be greater than 0" )
5+
6+ self .limit = limit
7+ self .cache = {}
8+ self .access_order = [] # most recent at the end
9+
10+ def get (self , key ):
11+ if key in self .cache :
12+ # Move to most recent position
13+ self .access_order .remove (key )
14+ self .access_order .append (key )
15+ return self .cache [key ]
16+ return None
17+
18+ def set (self , key , value ):
19+ if key in self .cache :
20+ # Update existing key
21+ self .cache [key ] = value
22+ # Move to most recent position
23+ self .access_order .remove (key )
24+ self .access_order .append (key )
25+ else :
26+ # New key
27+ if len (self .cache ) >= self .limit :
28+ # Remove least recently used (first item)
29+ lru_key = self .access_order [0 ]
30+ del self .cache [lru_key ]
31+ self .access_order .pop (0 )
32+
33+ # Add new key as most recent
34+ self .cache [key ] = value
35+ self .access_order .append (key )
Original file line number Diff line number Diff line change @@ -54,6 +54,46 @@ def test_eviction_order_after_gets(self):
5454 self .assertEqual (cache .get ("a" ), 1 )
5555 self .assertEqual (cache .get ("c" ), 3 )
5656
57+ def test_get_refreshes_item (self ):
58+ """Test that getting an item makes it recently used"""
59+ cache = LruCache (limit = 2 )
60+
61+ cache .set ("a" , 1 )
62+ cache .set ("b" , 2 )
63+
64+ # Access "a" to make it recently used
65+ cache .get ("a" )
66+
67+ # Add new item - should evict "b" not "a"
68+ cache .set ("c" , 3 )
69+
70+ self .assertIsNone (cache .get ("b" )) # "b" was evicted
71+ self .assertEqual (cache .get ("a" ), 1 ) # "a" remains
72+ self .assertEqual (cache .get ("c" ), 3 )
73+
74+ def test_complex_usage_pattern (self ):
75+ """Test LRU behavior with multiple operations"""
76+ cache = LruCache (limit = 3 )
77+
78+ # Add initial items
79+ cache .set ("a" , 1 )
80+ cache .set ("b" , 2 )
81+ cache .set ("c" , 3 )
82+
83+ # Use items in various order
84+ cache .get ("a" )
85+ cache .get ("c" )
86+ cache .get ("b" )
87+ cache .get ("a" )
88+
89+ # Add new item - should evict least recently used ("c")
90+ cache .set ("d" , 4 )
91+
92+ self .assertIsNone (cache .get ("c" )) # "c" was evicted
93+ self .assertEqual (cache .get ("a" ), 1 )
94+ self .assertEqual (cache .get ("b" ), 2 )
95+ self .assertEqual (cache .get ("d" ), 4 )
96+
5797
5898if __name__ == "__main__" :
5999 unittest .main ()
You can’t perform that action at this time.
0 commit comments