Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
68 changes: 68 additions & 0 deletions Sprint-2/implement_lru_cache/lru_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
from collections import OrderedDict

class LruCache:
def __init__(self, limit):
if limit <= 0:
raise ValueError("Limit must be positive")

self.limit = limit
<<<<<<< HEAD
self.cache = {} # key -> node
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

It seems a merge conflict has not yet been properly resolved.

self.head = None # Most recently used
self.tail = None # Least recently used

# ---------------------
# Internal helpers
# ---------------------

def _remove_node(self, node):
if node.previous:
node.previous.next = node.next
else:
self.head = node.next

if node.next:
node.next.previous = node.previous
else:
self.tail = node.previous

node.previous = None
node.next = None

def _add_to_head(self, node):
node.next = self.head
node.previous = None

if self.head:
self.head.previous = node
else:
self.tail = node

self.head = node

# ---------------------
# Public API
# ---------------------
=======
self.cache = OrderedDict()
>>>>>>> fc65c37 (lru cache update)

def get(self, key):
if key not in self.cache:
return None
# Move key to the end (most recently used)
value = self.cache.pop(key)
self.cache[key] = value
Comment on lines +15 to +16
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

OrderedDict has a built-in method that can replace these two operations.

return value

def set(self, key, value):
if key in self.cache:
# Update existing and move to end
self.cache.pop(key)

elif len(self.cache) >= self.limit:
# Remove least recently used (first item)
self.cache.popitem(last=False)

# Insert as most recently used
self.cache[key] = value
1 change: 0 additions & 1 deletion Sprint-2/implement_lru_cache/lru_cache_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import unittest

from lru_cache import LruCache

class LruCacheTest(unittest.TestCase):
Expand Down