热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Python实现的最近最少使用算法

这篇文章主要介绍了Python实现的最近最少使用算法,涉及节点、时间、流程控制等相关技巧,需要的朋友可以参考下
本文实例讲述了Python实现的最近最少使用算法。分享给大家供大家参考。具体如下:

# lrucache.py -- a simple LRU (Least-Recently-Used) cache class 
# Copyright 2004 Evan Prodromou  
# Licensed under the Academic Free License 2.1 
# Licensed for ftputil under the revised BSD license 
# with permission by the author, Evan Prodromou. Many 
# thanks, Evan! :-) 
# 
# The original file is available at 
# http://pypi.python.org/pypi/lrucache/0.2 . 
# arch-tag: LRU cache main module 
"""a simple LRU (Least-Recently-Used) cache module 
This module provides very simple LRU (Least-Recently-Used) cache 
functionality. 
An *in-memory cache* is useful for storing the results of an 
'expe\nsive' process (one that takes a lot of time or resources) for 
later re-use. Typical examples are accessing data from the filesystem, 
a database, or a network location. If you know you'll need to re-read 
the data again, it can help to keep it in a cache. 
You *can* use a Python dictionary as a cache for some purposes. 
However, if the results you're caching are large, or you have a lot of 
possible results, this can be impractical memory-wise. 
An *LRU cache*, on the other hand, only keeps _some_ of the results in 
memory, which keeps you from overusing resources. The cache is bounded 
by a maximum size; if you try to add more values to the cache, it will 
automatically discard the values that you haven't read or written to 
in the longest time. In other words, the least-recently-used items are 
discarded. [1]_ 
.. [1]: 'Discarded' here means 'removed from the cache'. 
"""
from __future__ import generators 
import time 
from heapq import heappush, heappop, heapify 
# the suffix after the hyphen denotes modifications by the 
# ftputil project with respect to the original version 
__version__ = "0.2-1"
__all__ = ['CacheKeyError', 'LRUCache', 'DEFAULT_SIZE'] 
__docformat__ = 'reStructuredText en'
DEFAULT_SIZE = 16
"""Default size of a new LRUCache object, if no 'size' argument is given."""
class CacheKeyError(KeyError): 
  """Error raised when cache requests fail 
  When a cache record is accessed which no longer exists (or never did), 
  this error is raised. To avoid it, you may want to check for the existence 
  of a cache record before reading or deleting it."""
  pass
class LRUCache(object): 
  """Least-Recently-Used (LRU) cache. 
  Instances of this class provide a least-recently-used (LRU) cache. They 
  emulate a Python mapping type. You can use an LRU cache more or less like 
  a Python dictionary, with the exception that objects you put into the 
  cache may be discarded before you take them out. 
  Some example usage:: 
  cache = LRUCache(32) # new cache 
  cache['foo'] = get_file_contents('foo') # or whatever 
  if 'foo' in cache: # if it's still in cache... 
    # use cached version 
    cOntents= cache['foo'] 
  else: 
    # recalculate 
    cOntents= get_file_contents('foo') 
    # store in cache for next time 
    cache['foo'] = contents 
  print cache.size # Maximum size 
  print len(cache) # 0 <= len(cache) <= cache.size 
  cache.size = 10 # Auto-shrink on size assignment 
  for i in range(50): # note: larger than cache size 
    cache[i] = i 
  if 0 not in cache: print 'Zero was discarded.' 
  if 42 in cache: 
    del cache[42] # Manual deletion 
  for j in cache:  # iterate (in LRU order) 
    print j, cache[j] # iterator produces keys, not values 
  """
  class __Node(object): 
    """Record of a cached value. Not for public consumption."""
    def __init__(self, key, obj, timestamp, sort_key): 
      object.__init__(self) 
      self.key = key 
      self.obj = obj 
      self.atime = timestamp 
      self.mtime = self.atime 
      self._sort_key = sort_key 
    def __cmp__(self, other): 
      return cmp(self._sort_key, other._sort_key) 
    def __repr__(self): 
      return "<%s %s => %s (%s)>" % \ 
          (self.__class__, self.key, self.obj, \ 
          time.asctime(time.localtime(self.atime))) 
  def __init__(self, size=DEFAULT_SIZE): 
    # Check arguments 
    if size <= 0: 
      raise ValueError, size 
    elif type(size) is not type(0): 
      raise TypeError, size 
    object.__init__(self) 
    self.__heap = [] 
    self.__dict = {} 
    """Maximum size of the cache. 
    If more than 'size' elements are added to the cache, 
    the least-recently-used ones will be discarded."""
    self.size = size 
    self.__counter = 0
  def _sort_key(self): 
    """Return a new integer value upon every call. 
    Cache nodes need a monotonically increasing time indicator. 
    time.time() and time.clock() don't guarantee this in a 
    platform-independent way. 
    """
    self.__counter += 1
    return self.__counter 
  def __len__(self): 
    return len(self.__heap) 
  def __contains__(self, key): 
    return self.__dict.has_key(key) 
  def __setitem__(self, key, obj): 
    if self.__dict.has_key(key): 
      node = self.__dict[key] 
      # update node object in-place 
      node.obj = obj 
      node.atime = time.time() 
      node.mtime = node.atime 
      node._sort_key = self._sort_key() 
      heapify(self.__heap) 
    else: 
      # size may have been reset, so we loop 
      while len(self.__heap) >= self.size: 
        lru = heappop(self.__heap) 
        del self.__dict[lru.key] 
      node = self.__Node(key, obj, time.time(), self._sort_key()) 
      self.__dict[key] = node 
      heappush(self.__heap, node) 
  def __getitem__(self, key): 
    if not self.__dict.has_key(key): 
      raise CacheKeyError(key) 
    else: 
      node = self.__dict[key] 
      # update node object in-place 
      node.atime = time.time() 
      node._sort_key = self._sort_key() 
      heapify(self.__heap) 
      return node.obj 
  def __delitem__(self, key): 
    if not self.__dict.has_key(key): 
      raise CacheKeyError(key) 
    else: 
      node = self.__dict[key] 
      del self.__dict[key] 
      self.__heap.remove(node) 
      heapify(self.__heap) 
      return node.obj 
  def __iter__(self): 
    copy = self.__heap[:] 
    while len(copy) > 0: 
      node = heappop(copy) 
      yield node.key 
    raise StopIteration 
  def __setattr__(self, name, value): 
    object.__setattr__(self, name, value) 
    # automagically shrink heap on resize 
    if name == 'size': 
      while len(self.__heap) > value: 
        lru = heappop(self.__heap) 
        del self.__dict[lru.key] 
  def __repr__(self): 
    return "<%s (%d elements)>" % (str(self.__class__), len(self.__heap)) 
  def mtime(self, key): 
    """Return the last modification time for the cache record with key. 
    May be useful for cache instances where the stored values can get 
    'stale', such as caching file or network resource contents."""
    if not self.__dict.has_key(key): 
      raise CacheKeyError(key) 
    else: 
      node = self.__dict[key] 
      return node.mtime 
if __name__ == "__main__": 
  cache = LRUCache(25) 
  print cache 
  for i in range(50): 
    cache[i] = str(i) 
  print cache 
  if 46 in cache: 
    print "46 in cache"
    del cache[46] 
  print cache 
  cache.size = 10
  print cache 
  cache[46] = '46'
  print cache 
  print len(cache) 
  for c in cache: 
    print c 
  print cache 
  print cache.mtime(46) 
  for c in cache: 
    print c 

希望本文所述对大家的Python程序设计有所帮助。

推荐阅读
  • Coursera ML 机器学习
    2019独角兽企业重金招聘Python工程师标准线性回归算法计算过程CostFunction梯度下降算法多变量回归![选择特征](https:static.oschina.n ... [详细]
  • 二维几何变换矩阵解析
    本文详细介绍了二维平面上的三种常见几何变换:平移、缩放和旋转。通过引入齐次坐标系,使得这些变换可以通过统一的矩阵乘法实现,从而简化了计算过程。文中不仅提供了理论推导,还附有Python代码示例,帮助读者更好地理解这些概念。 ... [详细]
  • Java 实现二维极点算法
    本文介绍了一种使用 Java 编程语言实现的二维极点算法。该算法用于从一组二维坐标中筛选出极点,适用于需要处理几何图形和空间数据的应用场景。文章不仅详细解释了算法的工作原理,还提供了完整的代码示例。 ... [详细]
  • 本题探讨了在大数据结构背景下,如何通过整体二分和CDQ分治等高级算法优化处理复杂的时间序列问题。题目设定包括节点数量、查询次数和权重限制,并详细分析了解决方案中的关键步骤。 ... [详细]
  • 本文介绍了数据库体系的基础知识,涵盖关系型数据库(如MySQL)和非关系型数据库(如MongoDB)的基本操作及高级功能。通过三个阶段的学习路径——基础、优化和部署,帮助读者全面掌握数据库的使用和管理。 ... [详细]
  • 智能车间调度研究进展
    本文综述了基于强化学习的智能车间调度策略,探讨了车间调度问题在资源有限条件下的优化方法。通过数学规划、智能算法和强化学习等手段,解决了作业车间、流水车间和加工车间中的静态与动态调度挑战。重点讨论了不同场景下的求解方法及其应用前景。 ... [详细]
  • 目录一、salt-job管理#job存放数据目录#缓存时间设置#Others二、returns模块配置job数据入库#配置returns返回值信息#mysql安全设置#创建模块相关 ... [详细]
  • 深入理解K近邻分类算法:机器学习100天系列(26)
    本文详细介绍了K近邻分类算法的理论基础,探讨其工作原理、应用场景以及潜在的局限性。作为机器学习100天系列的一部分,旨在为读者提供全面且深入的理解。 ... [详细]
  • 本文详细介绍了福昕软件公司开发的Foxit PDF SDK ActiveX控件(版本5.20),并提供了关于其在64位Windows 7系统和Visual Studio 2013环境下的使用方法。该控件文件名为FoxitPDFSDKActiveX520_Std_x64.ocx,适用于集成PDF功能到应用程序中。 ... [详细]
  • ZooKeeper集群脑裂问题及其解决方案
    本文深入探讨了ZooKeeper集群中可能出现的脑裂问题,分析其成因,并提供了多种有效的解决方案,确保集群在高可用性环境下的稳定运行。 ... [详细]
  • 本次挑战涉及数组截断操作,初看似乎简单,但实际上考察了对数组切片方法的理解与应用。本文将详细解析该算法的实现逻辑,并提供多个示例以加深理解。 ... [详细]
  • 本文深入探讨了Memcached的内存管理机制,特别是其采用的Slab Allocator技术。该技术通过预分配不同大小的内存块来有效解决内存碎片问题,并确保高效的数据存储与检索。文中详细描述了Slab Allocator的工作原理、内存分配流程以及相关的优化策略。 ... [详细]
  • 华为智慧屏:超越屏幕尺寸的智能进化
    继全球发布后,华为智慧屏于9月26日在上海正式亮相,推出65英寸和75英寸版本。该产品不仅在屏幕尺寸上有所突破,更在性能和智能化方面实现了显著提升。 ... [详细]
  • 本文介绍如何利用栈数据结构在C++中判断字符串中的括号是否匹配。通过顺序栈和链栈两种方式实现,并详细解释了算法的核心思想和具体实现步骤。 ... [详细]
  • Redux入门指南
    本文介绍Redux的基本概念和工作原理,帮助初学者理解如何使用Redux管理应用程序的状态。Redux是一个用于JavaScript应用的状态管理库,特别适用于React项目。 ... [详细]
author-avatar
云沏-茶
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有