对象为heappush的Python优先级队列不支持对象之间的'>'

2024-09-30 20:33:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在我尝试实现一个简单版本的*搜索时,我尝试将以下内容排入优先级队列:

  • 优先级:从源到当前元素的启发值和成本之和
  • 队列节点:具有数据成员点和成本的类队列节点的对象 代码是这样的: ''s=queueNode(开始,0) q、 放置((s.dist+启发式[s.pt[0]][s.pt[1]],s))#将源单元格“”排队

但是,它给出了以下错误: 输入 heappush(self.queue,item) 类型错误:'<;'在“queueNode”和“queueNode”的实例之间不受支持。

下面是类队列节点的代码

class queueNode:
    def __init__(self, pt, dist: int):
        self.pt = pt  # The cordinates of the cell
        self.dist = dist  # Cell's distance from the source

更新: 我试图通过这两个实现使类具有可比性

首先

class queueNode:
def __init__(self, pt, dist):
    self.pt = pt  # The cordinates of the cell
    self.dist = dist  # Cell's distance from the source

def __it__(self,other):
    return self.dist < other.dist

class queueNode:
def __init__(self, pt, dist):
    self.pt = pt  # The cordinates of the cell
    self.dist = dist  # Cell's distance from the source

def __it__(self,other):
    return id(self) < id(other)

它仍然给出相同的错误

更新: 解决方法是使用列表对象而不是优先级队列,并在每次输入新元素时对其进行排序。 代码 q=[] 追加 q、 追加((启发式[i][j],queueNodeObject)) 基于成本的排序

def sort(q):
    #start stop step
    for i in range(0,q.__len__(),1):
        for j in range(i+1,q.__len__()-1,1):
            if q[i][0]<q[j][0]:
#q[i] returns the element in queue list i.e tuple=(cost, object) q[i][0] returns #the cost
                temp=q[i]
                q[i]=q[j]
                q[j]=temp

Tags: the代码selfpt节点队列initdist