Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Sprint-2/implement_lru_cache/lru_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class LruCache:
def __init__(self, limit):
if limit <= 0:
raise ValueError("Limit must be greater than 0")

self.limit = limit
self.cache = {}
self.access_order = [] # most recent at the end

def get(self, key):
if key in self.cache:
# Move to most recent position
self.access_order.remove(key)
self.access_order.append(key)
return self.cache[key]
return None

def set(self, key, value):
if key in self.cache:
# Update existing key
self.cache[key] = value
# Move to most recent position
self.access_order.remove(key)
self.access_order.append(key)
else:
# New key
if len(self.cache) >= self.limit:
# Remove least recently used (first item)
lru_key = self.access_order[0]
del self.cache[lru_key]
self.access_order.pop(0)

# Add new key as most recent
self.cache[key] = value
self.access_order.append(key)
40 changes: 40 additions & 0 deletions Sprint-2/implement_lru_cache/lru_cache_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()