Skip to content

Commit 9eb3138

Browse files
ruppysuppycclauss
andauthored
Added LFU Cache (TheAlgorithms#2151)
* Added LFU Cache * Update lfu_cache.py * None is returned * Add type hints Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 27dde06 commit 9eb3138

File tree

1 file changed

+186
-0
lines changed

1 file changed

+186
-0
lines changed

other/lfu_cache.py

+186
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
from typing import Callable, Optional
2+
3+
4+
class DoubleLinkedListNode:
5+
'''
6+
Double Linked List Node built specifically for LFU Cache
7+
'''
8+
9+
def __init__(self, key: int, val: int):
10+
self.key = key
11+
self.val = val
12+
self.freq = 0
13+
self.next = None
14+
self.prev = None
15+
16+
17+
class DoubleLinkedList:
18+
'''
19+
Double Linked List built specifically for LFU Cache
20+
'''
21+
22+
def __init__(self):
23+
self.head = DoubleLinkedListNode(None, None)
24+
self.rear = DoubleLinkedListNode(None, None)
25+
self.head.next, self.rear.prev = self.rear, self.head
26+
27+
def add(self, node: DoubleLinkedListNode) -> None:
28+
'''
29+
Adds the given node at the head of the list and shifting it to proper position
30+
'''
31+
32+
temp = self.rear.prev
33+
34+
self.rear.prev, node.next = node, self.rear
35+
temp.next, node.prev = node, temp
36+
node.freq += 1
37+
self._position_node(node)
38+
39+
def _position_node(self, node: DoubleLinkedListNode) -> None:
40+
while node.prev.key and node.prev.freq > node.freq:
41+
node1, node2 = node, node.prev
42+
node1.prev, node2.next = node2.prev, node1.prev
43+
node1.next, node2.prev = node2, node1
44+
45+
def remove(self, node: DoubleLinkedListNode) -> DoubleLinkedListNode:
46+
'''
47+
Removes and returns the given node from the list
48+
'''
49+
50+
temp_last, temp_next = node.prev, node.next
51+
node.prev, node.next = None, None
52+
temp_last.next, temp_next.prev = temp_next, temp_last
53+
return node
54+
55+
56+
class LFUCache:
57+
'''
58+
LFU Cache to store a given capacity of data. Can be used as a stand-alone object
59+
or as a function decorator.
60+
61+
>>> cache = LFUCache(2)
62+
>>> cache.set(1, 1)
63+
>>> cache.set(2, 2)
64+
>>> cache.get(1)
65+
1
66+
>>> cache.set(3, 3)
67+
>>> cache.get(2) # None is returned
68+
>>> cache.set(4, 4)
69+
>>> cache.get(1) # None is returned
70+
>>> cache.get(3)
71+
3
72+
>>> cache.get(4)
73+
4
74+
>>> cache
75+
CacheInfo(hits=3, misses=2, capacity=2, current size=2)
76+
>>> @LFUCache.decorator(100)
77+
... def fib(num):
78+
... if num in (1, 2):
79+
... return 1
80+
... return fib(num - 1) + fib(num - 2)
81+
82+
>>> for i in range(1, 101):
83+
... res = fib(i)
84+
85+
>>> fib.cache_info()
86+
CacheInfo(hits=196, misses=100, capacity=100, current size=100)
87+
'''
88+
89+
# class variable to map the decorator functions to their respective instance
90+
decorator_function_to_instance_map = {}
91+
92+
def __init__(self, capacity: int):
93+
self.list = DoubleLinkedList()
94+
self.capacity = capacity
95+
self.num_keys = 0
96+
self.hits = 0
97+
self.miss = 0
98+
self.cache = {}
99+
100+
def __repr__(self) -> str:
101+
'''
102+
Return the details for the cache instance
103+
[hits, misses, capacity, current_size]
104+
'''
105+
106+
return (f'CacheInfo(hits={self.hits}, misses={self.miss}, '
107+
f'capacity={self.capacity}, current size={self.num_keys})')
108+
109+
def __contains__(self, key: int) -> bool:
110+
'''
111+
>>> cache = LFUCache(1)
112+
>>> 1 in cache
113+
False
114+
>>> cache.set(1, 1)
115+
>>> 1 in cache
116+
True
117+
'''
118+
return key in self.cache
119+
120+
def get(self, key: int) -> Optional[int]:
121+
'''
122+
Returns the value for the input key and updates the Double Linked List. Returns
123+
None if key is not present in cache
124+
'''
125+
126+
if key in self.cache:
127+
self.hits += 1
128+
self.list.add(self.list.remove(self.cache[key]))
129+
return self.cache[key].val
130+
self.miss += 1
131+
return None
132+
133+
def set(self, key: int, value: int) -> None:
134+
'''
135+
Sets the value for the input key and updates the Double Linked List
136+
'''
137+
138+
if key not in self.cache:
139+
if self.num_keys >= self.capacity:
140+
key_to_delete = self.list.head.next.key
141+
self.list.remove(self.cache[key_to_delete])
142+
del self.cache[key_to_delete]
143+
self.num_keys -= 1
144+
self.cache[key] = DoubleLinkedListNode(key, value)
145+
self.list.add(self.cache[key])
146+
self.num_keys += 1
147+
148+
else:
149+
node = self.list.remove(self.cache[key])
150+
node.val = value
151+
self.list.add(node)
152+
153+
@staticmethod
154+
def decorator(size: int = 128):
155+
'''
156+
Decorator version of LFU Cache
157+
'''
158+
159+
def cache_decorator_inner(func: Callable):
160+
161+
def cache_decorator_wrapper(*args, **kwargs):
162+
if func not in LFUCache.decorator_function_to_instance_map:
163+
LFUCache.decorator_function_to_instance_map[func] = LFUCache(size)
164+
165+
result = LFUCache.decorator_function_to_instance_map[func].get(args[0])
166+
if result is None:
167+
result = func(*args, **kwargs)
168+
LFUCache.decorator_function_to_instance_map[func].set(
169+
args[0], result
170+
)
171+
return result
172+
173+
def cache_info():
174+
return LFUCache.decorator_function_to_instance_map[func]
175+
176+
cache_decorator_wrapper.cache_info = cache_info
177+
178+
return cache_decorator_wrapper
179+
180+
return cache_decorator_inner
181+
182+
183+
if __name__ == "__main__":
184+
import doctest
185+
186+
doctest.testmod()

0 commit comments

Comments
 (0)