diff --git a/Sprint-2/implement_lru_cache/linked_list.py b/Sprint-2/implement_lru_cache/linked_list.py new file mode 100644 index 00000000..5999a955 --- /dev/null +++ b/Sprint-2/implement_lru_cache/linked_list.py @@ -0,0 +1,55 @@ +class Node: + __slots__ = ("value", "next", "previous") + + def __init__(self, value): + self.value = value + self.next = None + self.previous = None + +class LinkedList: + def __init__(self): + self.head = None + self.tail = None + + def push_head(self, value): + node = Node(value) + + if self.head is None: + self.head = node + self.tail = node + else: + node.next = self.head + self.head.previous = node + self.head = node + + return node + + def pop_tail(self): + node = self.tail + + if node is None: + return None + + self.remove(node) + + return node.value + + def remove(self, node): + if node == self.head and node == self.tail: + self.head = None + self.tail = None + + elif node == self.head: + self.head = node.next + self.head.previous = None + + elif node == self.tail: + self.tail = node.previous + self.tail.next = None + + else: + node.previous.next = node.next + node.next.previous = node.previous + + node.next = None + node.previous = None \ No newline at end of file diff --git a/Sprint-2/implement_lru_cache/lru_cache.py b/Sprint-2/implement_lru_cache/lru_cache.py index e69de29b..8e782bdf 100644 --- a/Sprint-2/implement_lru_cache/lru_cache.py +++ b/Sprint-2/implement_lru_cache/lru_cache.py @@ -0,0 +1,39 @@ +from linked_list import LinkedList + + +class LruCache: + def __init__(self, limit): + if limit <= 0: + raise ValueError("Limit must be greater than zero") + + self.limit = limit + self.cache = {} + self.order = LinkedList() + + def get(self, key): + if key not in self.cache: + return None + + node = self.cache[key] + value = node.value[1] + + # Move the accessed item to the head. + self.order.remove(node) + new_node = self.order.push_head(node.value) + self.cache[key] = new_node + + return value + + def set(self, key, value): + if key in self.cache: + node = self.cache[key] + self.order.remove(node) + + elif len(self.cache) >= self.limit: + # Remove the least recently used item. + lru_item = self.order.pop_tail() + del self.cache[lru_item[0]] + + # Add the item to the head as most recently used. + node = self.order.push_head((key, value)) + self.cache[key] = node \ No newline at end of file