MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / LRUCache

Class LRUCache

other/least_recently_used.py:10–74  ·  view source on GitHub ↗

Page Replacement Algorithm, Least Recently Used (LRU) Caching. >>> lru_cache: LRUCache[str | int] = LRUCache(4) >>> lru_cache.refer("A") >>> lru_cache.refer(2) >>> lru_cache.refer(3) >>> lru_cache LRUCache(4) => [3, 2, 'A'] >>> lru_cache.refer("A") >>> lru_cac

Source from the content-addressed store, hash-verified

8
9
10class LRUCache[T]:
11 """
12 Page Replacement Algorithm, Least Recently Used (LRU) Caching.
13
14 >>> lru_cache: LRUCache[str | int] = LRUCache(4)
15 >>> lru_cache.refer("A")
16 >>> lru_cache.refer(2)
17 >>> lru_cache.refer(3)
18
19 >>> lru_cache
20 LRUCache(4) => [3, 2, 'A']
21
22 >>> lru_cache.refer("A")
23 >>> lru_cache
24 LRUCache(4) => ['A', 3, 2]
25
26 >>> lru_cache.refer(4)
27 >>> lru_cache.refer(5)
28 >>> lru_cache
29 LRUCache(4) => [5, 4, 'A', 3]
30
31 """
32
33 dq_store: deque[T] # Cache store of keys
34 key_reference: set[T] # References of the keys in cache
35 _MAX_CAPACITY: int = 10 # Maximum capacity of cache
36
37 def __init__(self, n: int) -> None:
38 """Creates an empty store and map for the keys.
39 The LRUCache is set the size n.
40 """
41 self.dq_store = deque()
42 self.key_reference = set()
43 if not n:
44 LRUCache._MAX_CAPACITY = sys.maxsize
45 elif n < 0:
46 raise ValueError("n should be an integer greater than 0.")
47 else:
48 LRUCache._MAX_CAPACITY = n
49
50 def refer(self, x: T) -> None:
51 """
52 Looks for a page in the cache store and adds reference to the set.
53 Remove the least recently used key if the store is full.
54 Update store to reflect recent access.
55 """
56 if x not in self.key_reference:
57 if len(self.dq_store) == LRUCache._MAX_CAPACITY:
58 last_element = self.dq_store.pop()
59 self.key_reference.remove(last_element)
60 else:
61 self.dq_store.remove(x)
62
63 self.dq_store.appendleft(x)
64 self.key_reference.add(x)
65
66 def display(self) -> None:
67 """

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected