LFU Cache to store a given capacity of data. Can be used as a stand-alone object or as a function decorator. >>> cache = LFUCache(2) >>> cache.put(1, 1) >>> cache.put(2, 2) >>> cache.get(1) 1 >>> cache.put(3, 3) >>> cache.get(2) is None True >>> cache.pu
| 162 | |
| 163 | |
| 164 | class LFUCache[T, U]: |
| 165 | """ |
| 166 | LFU Cache to store a given capacity of data. Can be used as a stand-alone object |
| 167 | or as a function decorator. |
| 168 | |
| 169 | >>> cache = LFUCache(2) |
| 170 | >>> cache.put(1, 1) |
| 171 | >>> cache.put(2, 2) |
| 172 | >>> cache.get(1) |
| 173 | 1 |
| 174 | >>> cache.put(3, 3) |
| 175 | >>> cache.get(2) is None |
| 176 | True |
| 177 | >>> cache.put(4, 4) |
| 178 | >>> cache.get(1) is None |
| 179 | True |
| 180 | >>> cache.get(3) |
| 181 | 3 |
| 182 | >>> cache.get(4) |
| 183 | 4 |
| 184 | >>> cache |
| 185 | CacheInfo(hits=3, misses=2, capacity=2, current_size=2) |
| 186 | >>> @LFUCache.decorator(100) |
| 187 | ... def fib(num): |
| 188 | ... if num in (1, 2): |
| 189 | ... return 1 |
| 190 | ... return fib(num - 1) + fib(num - 2) |
| 191 | |
| 192 | >>> for i in range(1, 101): |
| 193 | ... res = fib(i) |
| 194 | |
| 195 | >>> fib.cache_info() |
| 196 | CacheInfo(hits=196, misses=100, capacity=100, current_size=100) |
| 197 | """ |
| 198 | |
| 199 | def __init__(self, capacity: int): |
| 200 | self.list: DoubleLinkedList[T, U] = DoubleLinkedList() |
| 201 | self.capacity = capacity |
| 202 | self.num_keys = 0 |
| 203 | self.hits = 0 |
| 204 | self.miss = 0 |
| 205 | self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} |
| 206 | |
| 207 | def __repr__(self) -> str: |
| 208 | """ |
| 209 | Return the details for the cache instance |
| 210 | [hits, misses, capacity, current_size] |
| 211 | """ |
| 212 | |
| 213 | return ( |
| 214 | f"CacheInfo(hits={self.hits}, misses={self.miss}, " |
| 215 | f"capacity={self.capacity}, current_size={self.num_keys})" |
| 216 | ) |
| 217 | |
| 218 | def __contains__(self, key: T) -> bool: |
| 219 | """ |
| 220 | >>> cache = LFUCache(1) |
| 221 |
no outgoing calls
no test coverage detected