Skip to content

Commit 9167c23

Browse files
committed
[mypy] Annotates other/least_recently_used over generic type
+ clean-up: rename key_reference to match type.
1 parent bec5109 commit 9167c23

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

other/least_recently_used.py

+13-10
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,47 @@
11
import sys
22
from collections import deque
3+
from typing import Generic, TypeVar
34

5+
T = TypeVar("T")
46

5-
class LRUCache:
7+
8+
class LRUCache(Generic[T]):
69
"""Page Replacement Algorithm, Least Recently Used (LRU) Caching."""
710

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
1013
_MAX_CAPACITY: int = 10 # Maximum capacity of cache
1114

12-
def __init__(self, n: int):
15+
def __init__(self, n: int) -> None:
1316
"""Creates an empty store and map for the keys.
1417
The LRUCache is set the size n.
1518
"""
1619
self.dq_store = deque()
17-
self.key_reference_map = set()
20+
self.key_reference = set()
1821
if not n:
1922
LRUCache._MAX_CAPACITY = sys.maxsize
2023
elif n < 0:
2124
raise ValueError("n should be an integer greater than 0.")
2225
else:
2326
LRUCache._MAX_CAPACITY = n
2427

25-
def refer(self, x):
28+
def refer(self, x: T) -> None:
2629
"""
2730
Looks for a page in the cache store and adds reference to the set.
2831
Remove the least recently used key if the store is full.
2932
Update store to reflect recent access.
3033
"""
31-
if x not in self.key_reference_map:
34+
if x not in self.key_reference:
3235
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
3336
last_element = self.dq_store.pop()
34-
self.key_reference_map.remove(last_element)
37+
self.key_reference.remove(last_element)
3538
else:
3639
self.dq_store.remove(x)
3740

3841
self.dq_store.appendleft(x)
39-
self.key_reference_map.add(x)
42+
self.key_reference.add(x)
4043

41-
def display(self):
44+
def display(self) -> None:
4245
"""
4346
Prints all the elements in the store.
4447
"""

0 commit comments

Comments
 (0)