为什么我的heapq中的元素未排序python?

时间:2018-10-04 13:19:19

标签: python python-3.x binary-heap edmonds-karp heapq

我正在python中使用带有自定义元素的简单heapq,并在其中实现了 lt 函数。

class Edge:
    def __init__(self, cost, u, v):
        self.u = u
        self.v = v
        self.cost = cost
    def weight(self):
        w = self.cost
        v = self.v
        while v.parent is not None:
            w += v.const
            v = v.parent
        return w

    def __lt__(self, other):
        return self.weight() < other.weight()

然后我将这些元素的堆放在另一个称为P的数组中:

class Vertex:
    def __init__(self, node=None):
        #other stuff omited ##### 
        self.P = []

    def add_incoming_nodes(self, subgraph):
        for node, costs in subgraph.items():
            #if costs[self.vertex] is not 0: #node is not self
            #push endpoints of the edge from another vertex to this vertex
            heapq.heappush(self.P, Edge(costs[self.vertex], node, self))

问题是当我对一个元素进行堆弹出时,我希望它是数组中最小的元素吧?但是这里的断言失败了

#select arbitrary vertex
a = all_nodes[0]
while a.P: #while P[a] is not ∅
    edge = heapq.heappop(a.P)
    for a_edge in a.P: 
        assert edge.weight() < a_edge.weight()

0 个答案:

没有答案