Skip to main content
 首页 » 编程设计

python之检查对象是否在堆内

2025年02月15日11JeffreyZhao

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

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__() 方法并引发了异常。