Skip to content

London | Nadika Zavodovska | Module-Complexity | Sprint 2 | Implement LRU cache #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
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
# Store items in order used
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 the value
return self.cache[key]

def set(self, key, value):
if key in self.cache:
# Mark as recently used
self.cache.move_to_end(key)
self.cache[key] = value
# Set or update value
if len(self.cache) > self.limit:
# Remove least used
self.cache.popitem(last=False)