-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcache.py
More file actions
61 lines (54 loc) · 1.51 KB
/
cache.py
File metadata and controls
61 lines (54 loc) · 1.51 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from HashTable import HashTable
from FrequencyList import FrequencyList
class CacheObject:
"""
Object to be stored in the cache
"""
def __init__(self, key, data):
self.data = data
self.key = key
self.parent = None
self.hash_reference = None
class LFUCache:
"""
Implementation of the proposed LFU cache data structure
"""
def __init__(self):
"""
Initializes an object
"""
self.table = HashTable()
self.list = FrequencyList()
def add(self, key, data):
"""
Add the data with key to cache.
:param key: Key of data to be inserted
:param data: Data to be cached
:return: None
"""
obj_data = self.table.search(key)
if obj_data:
obj_data.data += data
else:
cache_object = CacheObject(key, data)
self.list.insert_new(cache_object)
self.table.insert(cache_object)
def evict(self):
"""
Evict least frequently used cache item
:return: None
"""
cache_obj = self.list.delete_obj()
if cache_obj:
self.table.remove(cache_obj)
def retrieve(self, key):
"""
Retrieve cache object with key 'key'
:param key: key of the data to be retrieved
:return: Cache object
"""
cache_obj = self.table.search(key)
if cache_obj:
self.list.lookup(cache_obj)
return cache_obj
return None