python - 检查对象是否在堆内

标签 python heap

我正在尝试检查一个对象是否在堆中。但是,我不断收到此错误:

AttributeError: 'tuple' object has no attribute 'X'

我有一个 Heap 和一个 Cell 类,如下所示:

import heapq

class Heap(object):
    def __init__(self):
        self.heap = []

    def push(self, priority, cell):
        heapq.heappush(self.heap, (priority, cell))

    def pop(self):
        cell = heapq.heappop(self.heap)[1]
        return cell

    def contains(self, cell):
        if(cell in self.heap):
            return True
        return False

    def isEmpty(self):
        return len(self.heap) == 0

细胞类:

class Cell(object):
    def __init__(self, x, y):
        self.X = x
        self.Y = y

    def __eq__(self, other):
        return int(self.X) == int(other.X) and int(self.Y) == int(other.Y)

我这样使用 Heap 类:当我使用 contains 方法时出现错误。

from Heap import Heap
from Cell import Cell

class Test(object):
    def __init__(self):
        self.myHeap = Heap()
        cell = Cell(2, 3)

        self.myHeap.push(1, cell)

        if self.myHeap.contains(cell) == False:
            print("not in heap")

test = Test()

我做错了什么?任何帮助将不胜感激。

最佳答案

问题出在 contains 方法中。

def contains(self, cell):
    if(cell in self.heap):
        return True
    return False

self.head(priority, Cell) 类型的元组列表。您实际上将 Cells 与此列表(元组)的元素进行了比较,因此调用了 Cell.__eq__() 方法并引发了异常。

关于python - 检查对象是否在堆内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41927446/

相关文章:

python - Pandas 将 bool 值转换为实际值时出错

python - 根据值向网格图添加边框

python - 你在哪里存储 jinja 中的变量?

python - 在 Windows 上安装 python3 + lxml

c++ - 为什么插入到堆中比插入到未排序的列表中更快?

algorithm - 证明具有n个元素的二叉堆中二叉树的数量至多为O(log n)

python - 通过 Python Requests 模块发出 HTTP 请求不能通过 curl 的代理工作?为什么?

将最大堆转换为二叉搜索树

python - 如何在python中获取最大堆

c++ - 优先级队列和堆之间的区别