@@ -15,55 +15,55 @@ def __init__(self):
1515 self .head .next = self .tail #this is most recently used
1616 self .tail .previous = self .head #this is the least recently used
1717
18- def _add_to_head (self , node ):
18+ def add_to_head (self , node ):
1919 node .previous = self .head
2020 node .next = self .head .next
2121 self .head .next .previous = node
2222 self .head .next = node
2323
24- def _remove_node (self , node ):
24+ def remove_node (self , node ):
2525 prev = node .previous
2626 nxt = node .next
2727 prev .next = nxt
2828 nxt .previous = prev
2929
30- def _move_to_head (self , node ):
31- self ._remove_node (node )
32- self ._add_to_head (node )
30+ def move_to_head (self , node ):
31+ self .remove_node (node )
32+ self .add_to_head (node )
3333
34- def _pop_tail (self ):
34+ def pop_tail (self ):
3535 node = self .tail .previous
36- self ._remove_node (node )
36+ self .remove_node (node )
3737 return node
3838
3939
4040#Lru class for the logic
4141class LruCache :
42- def __init__ (self , limit ):
42+ def __init__ (self , limit ): #constructing
4343 if limit <= 0 :
44- raise ValueError ("Cache limit must be greater than zero" )
45- self .limit = limit
46- self .cache = {} #key->Node
47- self .dll = DoublyLinkedList ()
48- def get (self , key ):
44+ raise ValueError ("Cache limit must be greater than zero" ) #b/c it is not logical to have a cache with negative or 0 capacity
45+ self .limit = limit #to tell the limit of our cache
46+ self .cache = {} #empty cache with key->node
47+ self .dll = DoublyLinkedList () #i set the helper method as dll
48+ def get (self , key ): #Retrieve value and mark as recently used
4949 node = self .cache .get (key )
5050 if not node :
5151 return None
5252 # Move the node to the head (most recently used)
53- self .dll ._move_to_head (node )
53+ self .dll .move_to_head (node )
5454 return node .value
55- def set (self , key , value ):
55+ def set (self , key , value ): #Insert/update value and handle eviction
5656 node = self .cache .get (key )
5757 if node :
58- # Update existing node and move it to head
58+ #Update existing node and move it to head
5959 node .value = value
60- self .dll ._move_to_head (node )
60+ self .dll .move_to_head (node )
6161 else :
62- # Create a new node
62+ #Create a new node
6363 new_node = Node (key , value )
6464 self .cache [key ] = new_node
65- self .dll ._add_to_head (new_node )
65+ self .dll .add_to_head (new_node )
6666 if len (self .cache ) > self .limit :
6767 # Remove least recently used node
68- tail = self .dll ._pop_tail ()
68+ tail = self .dll .pop_tail ()
6969 del self .cache [tail .key ]
0 commit comments