同步操作将从 编程语言算法集/Python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
from __future__ import annotationsfrom typing import Callableclass DoubleLinkedListNode:"""Double Linked List Node built specifically for LFU Cache"""def __init__(self, key: int, val: int):self.key = keyself.val = valself.freq = 0self.next = Noneself.prev = Noneclass DoubleLinkedList:"""Double Linked List built specifically for LFU Cache"""def __init__(self):self.head = DoubleLinkedListNode(None, None)self.rear = DoubleLinkedListNode(None, None)self.head.next, self.rear.prev = self.rear, self.headdef add(self, node: DoubleLinkedListNode) -> None:"""Adds the given node at the head of the list and shifting it to proper position"""temp = self.rear.prevself.rear.prev, node.next = node, self.reartemp.next, node.prev = node, tempnode.freq += 1self._position_node(node)def _position_node(self, node: DoubleLinkedListNode) -> None:while node.prev.key and node.prev.freq > node.freq:node1, node2 = node, node.prevnode1.prev, node2.next = node2.prev, node1.prevnode1.next, node2.prev = node2, node1def remove(self, node: DoubleLinkedListNode) -> DoubleLinkedListNode:"""Removes and returns the given node from the list"""temp_last, temp_next = node.prev, node.nextnode.prev, node.next = None, Nonetemp_last.next, temp_next.prev = temp_next, temp_lastreturn nodeclass LFUCache:"""LFU Cache to store a given capacity of data. Can be used as a stand-alone objector as a function decorator.>>> cache = LFUCache(2)>>> cache.set(1, 1)>>> cache.set(2, 2)>>> cache.get(1)1>>> cache.set(3, 3)>>> cache.get(2) # None is returned>>> cache.set(4, 4)>>> cache.get(1) # None is returned>>> cache.get(3)3>>> cache.get(4)4>>> cacheCacheInfo(hits=3, misses=2, capacity=2, current_size=2)>>> @LFUCache.decorator(100)... def fib(num):... if num in (1, 2):... return 1... return fib(num - 1) + fib(num - 2)>>> for i in range(1, 101):... res = fib(i)>>> fib.cache_info()CacheInfo(hits=196, misses=100, capacity=100, current_size=100)"""# class variable to map the decorator functions to their respective instancedecorator_function_to_instance_map = {}def __init__(self, capacity: int):self.list = DoubleLinkedList()self.capacity = capacityself.num_keys = 0self.hits = 0self.miss = 0self.cache = {}def __repr__(self) -> str:"""Return the details for the cache instance[hits, misses, capacity, current_size]"""return (f"CacheInfo(hits={self.hits}, misses={self.miss}, "f"capacity={self.capacity}, current_size={self.num_keys})")def __contains__(self, key: int) -> bool:""">>> cache = LFUCache(1)>>> 1 in cacheFalse>>> cache.set(1, 1)>>> 1 in cacheTrue"""return key in self.cachedef get(self, key: int) -> int | None:"""Returns the value for the input key and updates the Double Linked List. ReturnsNone if key is not present in cache"""if key in self.cache:self.hits += 1self.list.add(self.list.remove(self.cache[key]))return self.cache[key].valself.miss += 1return Nonedef set(self, key: int, value: int) -> None:"""Sets the value for the input key and updates the Double Linked List"""if key not in self.cache:if self.num_keys >= self.capacity:key_to_delete = self.list.head.next.keyself.list.remove(self.cache[key_to_delete])del self.cache[key_to_delete]self.num_keys -= 1self.cache[key] = DoubleLinkedListNode(key, value)self.list.add(self.cache[key])self.num_keys += 1else:node = self.list.remove(self.cache[key])node.val = valueself.list.add(node)@staticmethoddef decorator(size: int = 128):"""Decorator version of LFU Cache"""def cache_decorator_inner(func: Callable):def cache_decorator_wrapper(*args, **kwargs):if func not in LFUCache.decorator_function_to_instance_map:LFUCache.decorator_function_to_instance_map[func] = LFUCache(size)result = LFUCache.decorator_function_to_instance_map[func].get(args[0])if result is None:result = func(*args, **kwargs)LFUCache.decorator_function_to_instance_map[func].set(args[0], result)return resultdef cache_info():return LFUCache.decorator_function_to_instance_map[func]cache_decorator_wrapper.cache_info = cache_inforeturn cache_decorator_wrapperreturn cache_decorator_innerif __name__ == "__main__":import doctestdoctest.testmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。