Why are the elements in my heapq not ordered python?

200 views Asked by At

I am using a simple heapq in python with custom elements on which I implemented the lt function.

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()

Then I keep a heap of these elements in another array called 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))

The problem is that when I heappop an element, I would expect it to be the smallest element in my array right ? But this assertion here fails

#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

There are 0 answers