hashheap python 实现

2023-05-16


class Node(object):
    """
    the type of class stored in the hashmap, in case there are many same heights
    in the heap, maintain the number
    """
    def __init__(self, id, num):
        self.id = id #id means its id in heap array
        self.num = num #number of same value in this id 处理重复元素
        
class HashHeap(object):
    def __init__(self, mode):
        self.heap = []
        self.mode = mode
        self.size = 0
        self.hash = {}
    def top(self):
        return self.heap[0] if len(self.heap) > 0 else 0
        
    def isempty(self):
        return len(self.heap) == 0
        
    def _comparesmall(self, a, b): #compare function in different mode
        if a <= b:
            if self.mode == 'min':
                return True
            else:
                return False
        else:
            if self.mode == 'min':
                return False
            else:
                return True
    def _swap(self, idA, idB): #swap two values in heap, we also need to change
        valA = self.heap[idA]
        valB = self.heap[idB]
        
        numA = self.hash[valA].num
        numB = self.hash[valB].num
        self.hash[valB] = Node(idA, numB)
        self.hash[valA] = Node(idB, numA)
        self.heap[idA], self.heap[idB] = self.heap[idB], self.heap[idA]
    
    def add(self, now):  #the key, height in this place
        self.size += 1
        if self.hash.get(now):
            hashnow = self.hash[now]
            self.hash[now] = Node(hashnow.id, hashnow.num + 1)
        else:
            self.heap.append(now)
            self.hash[now] = Node(len(self.heap) - 1,1)
            self._siftup(len(self.heap) - 1)
            
    def delete(self, now):
        self.size -= 1
        hashnow = self.hash[now]
        id = hashnow.id
        num = hashnow.num
        if num == 1:
            self._swap(id, len(self.heap)-1) #like the common delete operation
            self.hash.pop(now)
            self.heap.pop()
            if len(self.heap) > id:
                self._siftup(id)
                self._siftdown(id)
        else:
            self.hash[now] = Node(id, num - 1)
            
    def parent(self, id):
      if id == 0:
        return -1

      return (id - 1) / 2

    def _siftup(self,id):
        while abs(id -1)/2 < id :  #iterative version
            parentId = (id - 1)/2  #这里非常tricky.
            if self._comparesmall(self.heap[parentId],self.heap[id]):
                break
            else:
                self._swap(id, parentId)
            id = parentId
                
    def _siftdown(self, id): #iterative version
        while 2*id + 1 < len(self.heap):
            l = 2*id + 1
            r = l + 1
            small = id
            if self._comparesmall(self.heap[l], self.heap[id]):
                small = l
            if r < len(self.heap) and self._comparesmall(self.heap[r], self.heap[small]):
                small = r
            if small != id:
                self._swap(id, small)
            else:
                break
            id = small     

这个hashheap的实现可以既可以是最大堆,也可以是最小堆,同时因为hash表中存的value是在heap数组中的index和这个key值的数目,所以可以处理重复数字.关键在于siftup和siftdown的非递归实现.siftdown相当于heapify,但是之前只使用过递归版本.

转载于:https://www.cnblogs.com/sherylwang/p/5652943.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

hashheap python 实现 的相关文章

  • 如何让“conda”安装程序查找“PyPi”包

    我试图使用conda http conda pydata org docs using pkgs html managing packages包管理器来安装我的 Python 包 最近 我遇到了 Anaconda org 存储库中不存在我需
  • 导入错误:无法导入名称“FFProbe”

    我无法获取ffprobe包 https github com simonh10 ffprobe在 Python 3 6 中工作 我使用 pip 安装它 但是当我输入import ffprobe it says Traceback most
  • GUI 测试工具 PyUseCase 与 Dogtail 相比如何?

    GUI测试工具如何Py用例 http pypi python org pypi PyUseCase重命名为故事文本 http pypi python org pypi StoryText 相比于Dogtail http en wikiped
  • 如何同时运行多个功能[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我有以下代码 my func1 my func2 my func3 my func4 my func5 是否可以同时计算函数的数据 而
  • 如何通过 python 中的函数运行列表?

    我试图通过我创建的函数运行我的列表 但不断收到错误 我不知道出了什么问题 温度 F temp f 19 21 21 21 23 功能 def fahrToCelsius tempFahrenheit return tempFahrenhei
  • Python 不考虑 distutils.cfg

    我已经尝试了给出的所有内容 并且所有教程都指向相同的方向 即使用 mingw 作为 python 而不是 Visual C 中的编译器 我确实有 Visual C 和 mingw 当我想使用 pip 安装时 问题开始出现 它总是给Unabl
  • Scrapy 文件管道不下载文件

    我的任务是构建一个可以下载所有内容的网络爬虫 pdfs 在给定站点中 Spider 在本地计算机和抓取集线器上运行 由于某种原因 当我运行它时 它只下载一些但不是全部的 pdf 通过查看输出中的项目可以看出这一点JSON 我已经设定MEDI
  • 使用 Tkinter 打开网页

    因此 我的应用程序需要能够打开其中的单个网页 并且它必须来自互联网并且未保存 特别是我想使用 Tkinter GUI 工具包 因为它是我最熟悉的工具包 最重要的是 我希望能够在窗口中生成事件 例如单击鼠标 但无需实际使用鼠标 有什么好的方法
  • 为什么需要设置WORKON_HOME环境变量?

    我已经有一段时间没有使用 python 虚拟环境了 但我也安装了虚拟环境包装器 我的问题是 在文档页面中它说要这样做 export WORKON HOME Envs mkdir p WORKON HOME source usr local
  • 在 django 中导入设置时出现奇怪的错误

    我有很多项目在 ubuntu 中使用 python2 7 和 virtualenv virtualenvwrapper 工作 在我的工作中 一些开发人员使用 macosx 和 windows 通常我像往常一样创建项目 django admi
  • pandas groupby 操作缺少数据

    在 pandas 数据框中 我有一列如下所示 0 M 1 E 2 L 3 M 1 4 M 2 5 M 3 6 E 1 7 E 2 8 E 3 9 E 4 10 L 1 11 L 2 12 M 1 a 13 M 1 b 14 M 1 c 15
  • 将图与热图(可能是对数)配对?

    How to create a pair plot in Python like the following but with heat maps instead of points or instead of a hex bin plot
  • 哪种方式最适合Python工厂注册?

    这是一个关于这些方法中哪一种被认为是最有效的问题 Pythonic 我不是在寻找个人意见 而是在寻找惯用的观点 我的背景不是Python 所以这会对我有帮助 我正在开发一个可扩展的 Python 3 项目 这个想法类似于工厂模式 只不过它是
  • 如何将 URL 添加到 Telegram Bot 的 InlineKeyboardButton

    我想制作一个按钮 可以从 Telegram 聊天中在浏览器中打开 URL 外部超链接 目前 我只开发了可点击的操作按钮 update message reply text Subscribe to us on Facebook and Te
  • 在Python中使用pil读取tif图像时出现值错误?

    我必须读取尺寸的tif图像2200 2200并输入 uint16 我将 PIL 库与 anaconda python 一起使用 如下所示 from PIL import Image img Image open test tif img i
  • 如何检测一个二维数组是否在另一个二维数组内?

    因此 在堆栈溢出成员的帮助下 我得到了以下代码 data needle s which is a png image base64 code goes here decoded data decode base64 f cStringIO
  • 如何在引发异常时将变量传递给异常并在异常时检索它?

    现在我只有一个空白的异常类 我想知道如何在引发变量时给它一个变量 然后在 try except 中处理它时检索该变量 class ExampleException Exception pass 为其构造函数提供一个参数 将其存储为属性 然后
  • 为什么从 openAI 导入 Universe 模块时出现“无效语法”错误

    当我导入时universe来自 openAI 的模块 我收到以下错误 Traceback most recent call last File
  • py2exe ImportError:没有名为 的模块

    我已经实现了一个名为 myUtils 的包 它由文件夹 myUtils 文件 组成 init py 和许多名称为 myUtils 的 py 文件 该包包含在 myOtherProject py 中 当我从 Eclipse 运行它们时可以找到
  • Tkinter 将鼠标点击绑定到框架

    我一定错过了一些明显的东西 我的 Tkinter 程序中有两个框架 每个框架在网格布局中都有一堆标签 我想将鼠标点击绑定到其中一个而不是另一个 我目前使用 root bind

随机推荐