微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有对象heappush的Python优先级队列不支持对象之间的“>”

如何解决带有对象heappush的Python优先级队列不支持对象之间的“>”

在尝试实现A * Search的简单版本时,我尝试将以下内容放入优先级队列:

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

但是,它出现以下错误以_put表示 heappush(self.queue,项目) TypeError:“ 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,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,other):
    return id(self) < id(other)

它仍然给出相同的错误

更新: 一种解决方法是使用列表对象代替优先级队列,并在每次输入新元素时对其进行排序。 CODE q = [] 追加 q.append((启发式[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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。