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


class LruCache:
def __init__(self, limit):
if limit < 1:
raise ValueError("Limit cannot be less than 1")
self.limit = limit
self.storage = OrderedDict()

def set(self, key, value):
if len(self.storage) < self.limit:
self.storage[key] = value
else:
self.storage.popitem(last=False)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

If the cache is full and you set something which is already in the cache, what happens?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

It would remove the least recently used item and update the value of the existing one. I fixed this by adding a membership check: if the item is already in the cache, it’s moved to the end and its value is updated.

self.storage[key] = value

def get(self, key):
if key in self.storage:
self.storage.move_to_end(key)
return self.storage[key]
return None