-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlfu_cache.py
More file actions
25 lines (21 loc) · 770 Bytes
/
Copy pathlfu_cache.py
File metadata and controls
25 lines (21 loc) · 770 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from collections import defaultdict
class LFUCache:
def __init__(self, capacity_kb):
self.capacity = capacity_kb
self.cache = {}
self.freq = defaultdict(int)
self.current_size = 0
def request_page(self, page, size_kb):
if page in self.cache:
self.freq[page] += 1
return True # Cache hit
# Cache miss → add page
while self.current_size + size_kb > self.capacity:
least_used = min(self.freq, key=self.freq.get)
self.current_size -= self.cache[least_used]
del self.cache[least_used]
del self.freq[least_used]
self.cache[page] = size_kb
self.freq[page] = 1
self.current_size += size_kb
return False