|
1 | 1 | import sys
|
2 | 2 | from collections import deque
|
| 3 | +from typing import Generic, TypeVar |
3 | 4 |
|
| 5 | +T = TypeVar("T") |
4 | 6 |
|
5 |
| -class LRUCache: |
| 7 | + |
| 8 | +class LRUCache(Generic[T]): |
6 | 9 | """Page Replacement Algorithm, Least Recently Used (LRU) Caching."""
|
7 | 10 |
|
8 |
| - dq_store = object() # Cache store of keys |
9 |
| - key_reference_map = object() # References of the keys in cache |
| 11 | + dq_store: deque[T] # Cache store of keys |
| 12 | + key_reference: set[T] # References of the keys in cache |
10 | 13 | _MAX_CAPACITY: int = 10 # Maximum capacity of cache
|
11 | 14 |
|
12 |
| - def __init__(self, n: int): |
| 15 | + def __init__(self, n: int) -> None: |
13 | 16 | """Creates an empty store and map for the keys.
|
14 | 17 | The LRUCache is set the size n.
|
15 | 18 | """
|
16 | 19 | self.dq_store = deque()
|
17 |
| - self.key_reference_map = set() |
| 20 | + self.key_reference = set() |
18 | 21 | if not n:
|
19 | 22 | LRUCache._MAX_CAPACITY = sys.maxsize
|
20 | 23 | elif n < 0:
|
21 | 24 | raise ValueError("n should be an integer greater than 0.")
|
22 | 25 | else:
|
23 | 26 | LRUCache._MAX_CAPACITY = n
|
24 | 27 |
|
25 |
| - def refer(self, x): |
| 28 | + def refer(self, x: T) -> None: |
26 | 29 | """
|
27 | 30 | Looks for a page in the cache store and adds reference to the set.
|
28 | 31 | Remove the least recently used key if the store is full.
|
29 | 32 | Update store to reflect recent access.
|
30 | 33 | """
|
31 |
| - if x not in self.key_reference_map: |
| 34 | + if x not in self.key_reference: |
32 | 35 | if len(self.dq_store) == LRUCache._MAX_CAPACITY:
|
33 | 36 | last_element = self.dq_store.pop()
|
34 |
| - self.key_reference_map.remove(last_element) |
| 37 | + self.key_reference.remove(last_element) |
35 | 38 | else:
|
36 | 39 | self.dq_store.remove(x)
|
37 | 40 |
|
38 | 41 | self.dq_store.appendleft(x)
|
39 |
| - self.key_reference_map.add(x) |
| 42 | + self.key_reference.add(x) |
40 | 43 |
|
41 |
| - def display(self): |
| 44 | + def display(self) -> None: |
42 | 45 | """
|
43 | 46 | Prints all the elements in the store.
|
44 | 47 | """
|
|
0 commit comments