gpt4 book ai didi

python - 检查对象是否在堆内

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:09 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com