-
-
Notifications
You must be signed in to change notification settings - Fork 46.9k
Added LRU Cache #2138
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
Added LRU Cache #2138
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -1,49 +1,55 @@ | ||||||||||||||||||||
class Double_Linked_List_Node(): | ||||||||||||||||||||
from typing import Optional, Callable | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
class DoubleLinkedListNode: | ||||||||||||||||||||
''' | ||||||||||||||||||||
Double Linked List Node built specifically for LRU Cache | ||||||||||||||||||||
''' | ||||||||||||||||||||
|
||||||||||||||||||||
def __init__(self, key, val): | ||||||||||||||||||||
def __init__(self, key: int, val: int): | ||||||||||||||||||||
self.key = key | ||||||||||||||||||||
self.val = val | ||||||||||||||||||||
self.next = None | ||||||||||||||||||||
self.prev = None | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
class Double_Linked_List(): | ||||||||||||||||||||
class DoubleLinkedList: | ||||||||||||||||||||
''' | ||||||||||||||||||||
Double Linked List built specifically for LRU Cache | ||||||||||||||||||||
''' | ||||||||||||||||||||
|
||||||||||||||||||||
def __init__(self): | ||||||||||||||||||||
self.head = Double_Linked_List_Node(None, None) | ||||||||||||||||||||
self.rear = Double_Linked_List_Node(None, None) | ||||||||||||||||||||
self.head = DoubleLinkedListNode(None, None) | ||||||||||||||||||||
self.rear = DoubleLinkedListNode(None, None) | ||||||||||||||||||||
self.head.next, self.rear.prev = self.rear, self.head | ||||||||||||||||||||
|
||||||||||||||||||||
def add(self, node: Double_Linked_List_Node) -> None: | ||||||||||||||||||||
def add(self, node: DoubleLinkedListNode) -> None: | ||||||||||||||||||||
''' | ||||||||||||||||||||
Adds the given node to the end of the list (before rear) | ||||||||||||||||||||
''' | ||||||||||||||||||||
|
||||||||||||||||||||
temp = self.rear.prev | ||||||||||||||||||||
temp.next, node.prev = node, temp | ||||||||||||||||||||
self.rear.prev, node.next = node, self.rear | ||||||||||||||||||||
|
||||||||||||||||||||
def remove(self, node: Double_Linked_List_Node) -> Double_Linked_List_Node: | ||||||||||||||||||||
def remove(self, node: DoubleLinkedListNode) -> DoubleLinkedListNode: | ||||||||||||||||||||
''' | ||||||||||||||||||||
Removes and returns the given node from the list | ||||||||||||||||||||
''' | ||||||||||||||||||||
|
||||||||||||||||||||
temp_last, temp_next = node.prev, node.next | ||||||||||||||||||||
node.prev, node.next = None, None | ||||||||||||||||||||
temp_last.next, temp_next.prev = temp_next, temp_last | ||||||||||||||||||||
|
||||||||||||||||||||
return node | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
class Lru_Cache: | ||||||||||||||||||||
class LruCache: | ||||||||||||||||||||
cclauss marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||||||||
''' | ||||||||||||||||||||
LRU Cache to store a given capacity of data | ||||||||||||||||||||
LRU Cache to store a given capacity of data. Can be used as a stand-alone object | ||||||||||||||||||||
or as a function decorator. | ||||||||||||||||||||
|
||||||||||||||||||||
>>> cache = Lru_Cache(2) | ||||||||||||||||||||
>>> cache = LruCache(2) | ||||||||||||||||||||
|
||||||||||||||||||||
>>> cache.set(1, 1) | ||||||||||||||||||||
|
||||||||||||||||||||
|
@@ -54,58 +60,70 @@ class Lru_Cache: | |||||||||||||||||||
|
||||||||||||||||||||
>>> cache.set(3, 3) | ||||||||||||||||||||
|
||||||||||||||||||||
>>> cache.get(2) | ||||||||||||||||||||
Traceback (most recent call last): | ||||||||||||||||||||
... | ||||||||||||||||||||
ValueError: Key '2' not found in cache | ||||||||||||||||||||
>>> cache.get(2) # None returned | ||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why get rid of the exception? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Its given in the type hint, the function will return an integer or None if the key is absent |
||||||||||||||||||||
|
||||||||||||||||||||
>>> cache.set(4, 4) | ||||||||||||||||||||
|
||||||||||||||||||||
>>> cache.get(1) | ||||||||||||||||||||
Traceback (most recent call last): | ||||||||||||||||||||
... | ||||||||||||||||||||
ValueError: Key '1' not found in cache | ||||||||||||||||||||
>>> cache.get(1) # None returned | ||||||||||||||||||||
|
||||||||||||||||||||
>>> cache.get(3) | ||||||||||||||||||||
3 | ||||||||||||||||||||
|
||||||||||||||||||||
>>> cache.get(4) | ||||||||||||||||||||
4 | ||||||||||||||||||||
|
||||||||||||||||||||
>>> cache.has_key(1) | ||||||||||||||||||||
False | ||||||||||||||||||||
>>> cache.cache_info() | ||||||||||||||||||||
'CacheInfo(hits=3, misses=2, capacity=2, current size=2)' | ||||||||||||||||||||
|
||||||||||||||||||||
>>> @LruCache.decorator(100) | ||||||||||||||||||||
... def fib(num): | ||||||||||||||||||||
... if num in (1, 2): | ||||||||||||||||||||
... return 1 | ||||||||||||||||||||
... return fib(num - 1) + fib(num - 2) | ||||||||||||||||||||
|
||||||||||||||||||||
>>> cache.has_key(4) | ||||||||||||||||||||
True | ||||||||||||||||||||
>>> for i in range(1, 100): | ||||||||||||||||||||
... res = fib(i) | ||||||||||||||||||||
|
||||||||||||||||||||
>>> fib.cache_info() | ||||||||||||||||||||
'CacheInfo(hits=194, misses=99, capacity=100, current size=99)' | ||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. AWESOME!!! |
||||||||||||||||||||
''' | ||||||||||||||||||||
|
||||||||||||||||||||
def __init__(self, capacity): | ||||||||||||||||||||
self.list = Double_Linked_List() | ||||||||||||||||||||
# class variable to map the decorator functions to their respective instance | ||||||||||||||||||||
decorator_function_to_instance_map = {} | ||||||||||||||||||||
|
||||||||||||||||||||
def __init__(self, capacity: int): | ||||||||||||||||||||
self.list = DoubleLinkedList() | ||||||||||||||||||||
self.capacity = capacity | ||||||||||||||||||||
self.num_keys = 0 | ||||||||||||||||||||
self.hits = 0 | ||||||||||||||||||||
self.miss = 0 | ||||||||||||||||||||
self.cache = {} | ||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why have both a cache and a decorator_function_to_instance_map? Could we have one instead of two? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We need both as the cache maps the keys to the Double Linked List Node |
||||||||||||||||||||
|
||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Thanks a lot :) 👍 |
||||||||||||||||||||
def get(self, key: int) -> int: | ||||||||||||||||||||
def get(self, key: int) -> Optional[int]: | ||||||||||||||||||||
''' | ||||||||||||||||||||
Returns the value for the input key and updates the Double Linked List. Raises | ||||||||||||||||||||
Value Error if key is not present in cache | ||||||||||||||||||||
Returns the value for the input key and updates the Double Linked List. Returns | ||||||||||||||||||||
None if key is not present in cache | ||||||||||||||||||||
''' | ||||||||||||||||||||
|
||||||||||||||||||||
if key in self.cache: | ||||||||||||||||||||
self.hits += 1 | ||||||||||||||||||||
self.list.add(self.list.remove(self.cache[key])) | ||||||||||||||||||||
return self.cache[key].val | ||||||||||||||||||||
raise ValueError(f"Key '{key}' not found in cache") | ||||||||||||||||||||
self.miss += 1 | ||||||||||||||||||||
return None | ||||||||||||||||||||
|
||||||||||||||||||||
def set(self, key: int, value: int) -> None: | ||||||||||||||||||||
''' | ||||||||||||||||||||
Sets the value for the input key and updates the Double Linked List | ||||||||||||||||||||
''' | ||||||||||||||||||||
|
||||||||||||||||||||
if key not in self.cache: | ||||||||||||||||||||
if self.num_keys >= self.capacity: | ||||||||||||||||||||
key_to_delete = self.list.head.next.key | ||||||||||||||||||||
self.list.remove(self.cache[key_to_delete]) | ||||||||||||||||||||
del self.cache[key_to_delete] | ||||||||||||||||||||
self.num_keys -= 1 | ||||||||||||||||||||
self.cache[key] = Double_Linked_List_Node(key, value) | ||||||||||||||||||||
self.cache[key] = DoubleLinkedListNode(key, value) | ||||||||||||||||||||
self.list.add(self.cache[key]) | ||||||||||||||||||||
self.num_keys += 1 | ||||||||||||||||||||
|
||||||||||||||||||||
|
@@ -114,11 +132,46 @@ def set(self, key: int, value: int) -> None: | |||||||||||||||||||
node.val = value | ||||||||||||||||||||
self.list.add(node) | ||||||||||||||||||||
|
||||||||||||||||||||
def has_key(self, key: int) -> bool: | ||||||||||||||||||||
def cache_info(self) -> str: | ||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
This allows us to just There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. using repr to use |
||||||||||||||||||||
''' | ||||||||||||||||||||
Checks if the input key is present in cache | ||||||||||||||||||||
Returns the details for the cache instance | ||||||||||||||||||||
[hits, misses, capacity, current size] | ||||||||||||||||||||
cclauss marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||||||||
''' | ||||||||||||||||||||
return key in self.cache | ||||||||||||||||||||
|
||||||||||||||||||||
return f'CacheInfo(hits={self.hits}, misses={self.miss}, \ | ||||||||||||||||||||
capacity={self.capacity}, current size={self.num_keys})' | ||||||||||||||||||||
cclauss marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||||||||
|
||||||||||||||||||||
@staticmethod | ||||||||||||||||||||
def decorator(size: int = 128): | ||||||||||||||||||||
''' | ||||||||||||||||||||
Decorator version of LRU Cache | ||||||||||||||||||||
''' | ||||||||||||||||||||
|
||||||||||||||||||||
def cache_decorator_inner(func: Callable): | ||||||||||||||||||||
|
||||||||||||||||||||
def cache_decorator_wrapper(*args, **kwargs): | ||||||||||||||||||||
if func not in LruCache.decorator_function_to_instance_map: | ||||||||||||||||||||
LruCache.decorator_function_to_instance_map[func] = LruCache(size) | ||||||||||||||||||||
|
||||||||||||||||||||
result = LruCache.decorator_function_to_instance_map[func].get(args[0]) | ||||||||||||||||||||
|
||||||||||||||||||||
if result is not None: | ||||||||||||||||||||
return result | ||||||||||||||||||||
|
||||||||||||||||||||
result = func(*args, **kwargs) | ||||||||||||||||||||
LruCache.decorator_function_to_instance_map[func].set(args[0], result) | ||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. using |
||||||||||||||||||||
return result | ||||||||||||||||||||
|
||||||||||||||||||||
def cache_info(): | ||||||||||||||||||||
if func not in LruCache.decorator_function_to_instance_map: | ||||||||||||||||||||
return "Cache for function not initialized" | ||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this raise an Exception? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, but later realized, its an impossible case, so removed it |
||||||||||||||||||||
return LruCache.decorator_function_to_instance_map[func].cache_info() | ||||||||||||||||||||
|
||||||||||||||||||||
cache_decorator_wrapper.cache_info = cache_info | ||||||||||||||||||||
|
||||||||||||||||||||
return cache_decorator_wrapper | ||||||||||||||||||||
|
||||||||||||||||||||
return cache_decorator_inner | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
if __name__ == "__main__": | ||||||||||||||||||||
|
Uh oh!
There was an error while loading. Please reload this page.