检查堆内是否有对象

时间:2017-01-30 00:17:48

标签: 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()

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

1 个答案:

答案 0 :(得分:1)

问题出在contains方法中。

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

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