diff --git a/.gitignore b/.gitignore index bfb5886..6127881 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .DS_Store -node_modules +node_modules/ .venv __pycache__ +venv/ diff --git a/Sprint-2/implement_lru_cache/lru_cache.py b/Sprint-2/implement_lru_cache/lru_cache.py index e69de29..57bba7b 100644 --- a/Sprint-2/implement_lru_cache/lru_cache.py +++ b/Sprint-2/implement_lru_cache/lru_cache.py @@ -0,0 +1,27 @@ +from collections import OrderedDict + +class LruCache: + def __init__(self, limit): + if limit <= 0: + raise ValueError("Limit must be greater than 0") + self.limit = limit + self.cache = OrderedDict() + + def get(self, key): + if key not in self.cache: + return None + + # Mark as recently used + self.cache.move_to_end(key) + return self.cache[key] + + def set(self, key, value): + if key in self.cache: + + self.cache.move_to_end(key) + + self.cache[key] = value + + # Evict least recently used item + if len(self.cache) > self.limit: + self.cache.popitem(last=False) diff --git a/Sprint-2/implement_lru_cache/lru_cache_test.py b/Sprint-2/implement_lru_cache/lru_cache_test.py index d37df01..314da14 100644 --- a/Sprint-2/implement_lru_cache/lru_cache_test.py +++ b/Sprint-2/implement_lru_cache/lru_cache_test.py @@ -54,6 +54,46 @@ def test_eviction_order_after_gets(self): self.assertEqual(cache.get("a"), 1) self.assertEqual(cache.get("c"), 3) + def test_get_refreshes_item(self): + """Test that getting an item makes it recently used""" + cache = LruCache(limit=2) + + cache.set("a", 1) + cache.set("b", 2) + + # Access "a" to make it recently used + cache.get("a") + + # Add new item - should evict "b" not "a" + cache.set("c", 3) + + self.assertIsNone(cache.get("b")) # "b" was evicted + self.assertEqual(cache.get("a"), 1) # "a" remains + self.assertEqual(cache.get("c"), 3) + + def test_complex_usage_pattern(self): + """Test LRU behavior with multiple operations""" + cache = LruCache(limit=3) + + # Add initial items + cache.set("a", 1) + cache.set("b", 2) + cache.set("c", 3) + + # Use items in various order + cache.get("a") + cache.get("c") + cache.get("b") + cache.get("a") + + # Add new item - should evict least recently used ("c") + cache.set("d", 4) + + self.assertIsNone(cache.get("c")) # "c" was evicted + self.assertEqual(cache.get("a"), 1) + self.assertEqual(cache.get("b"), 2) + self.assertEqual(cache.get("d"), 4) + if __name__ == "__main__": unittest.main()