检查对象是否在堆内

Checking if object inside heap

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

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

我有一个 Heap 和一个 Cell class 看起来像这样:

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:

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 class: 当我使用 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__() 方法并引发异常。