From eb34b849b643e478286117f2c469ff5effb81fc0 Mon Sep 17 00:00:00 2001 From: Raihan Sharif Date: Sat, 24 Oct 2026 08:03:53 +0100 Subject: [PATCH] implement LRU cache using OrderedDict Was going to use my own linked list, this was easier. --- Sprint-2/implement_lru_cache/lru_cache.py | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Sprint-2/implement_lru_cache/lru_cache.py b/Sprint-2/implement_lru_cache/lru_cache.py index e69de29b..6d2a8bbf 100644 --- a/Sprint-2/implement_lru_cache/lru_cache.py +++ b/Sprint-2/implement_lru_cache/lru_cache.py @@ -0,0 +1,26 @@ +from collections import OrderedDict +""" +Was gonna implement my own using a dict to to store keys and +my own doubly linked list to do the ordering. I'm not 100% sure about the complexity +of the OrderedDict, but it should be O(1) for get and set. +""" + +class LruCache: + def __init__(self, limit): + if limit <= 0: + raise ValueError("Limit must be greater than 0") + self.limit = limit + self.data = OrderedDict() + + def get(self, key): + if key not in self.data: + return None + self.data.move_to_end(key) # end is most recent + return self.data[key] + + def set(self, key, value): + if key in self.data: + self.data.move_to_end(key) + self.data[key] = value + if len(self.data) > self.limit: + self.data.popitem(last=False) \ No newline at end of file