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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.DS_Store
node_modules
node_modules/
.venv
__pycache__
venv/
27 changes: 27 additions & 0 deletions Sprint-2/implement_lru_cache/lru_cache.py
Original file line number Diff line number Diff line change
@@ -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)
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):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to see these additional tests. You're the only one I've seen so far that has added these tests.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oooh thank you, David.

"""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()