heapq自定义compareTo

时间:2018-10-26 18:01:17

标签: python sorting priority-queue heapq

我正在尝试定义一个custome方法,以便在python中的优先级队列中进行有序插入,但未获得预期的结果。一旦定义了插入方法到队列中,如下所示:

def insert(self, node):
    if isinstance(node, treeNode):
        heapq.heappush(self._frontier, (node._f, node))
    else:
        print("Error. It is not a node.")

并在'node'类中实现以下 lt

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

插入不是通过'f'属性值完成的,这是我想做的,请按该值确定的升序插入。任何帮助将不胜感激。

失败的例子:

[(141.09530289033592, <treeNode.treeNode object at 0x7f08bb840fd0>), (484.8315227978057, <treeNode.treeNode object at 0x7f08bb849da0>), (390.0514031446352, <treeNode.treeNode object at 0x7f08bb840e48>)]

它仅将最低位置放在第一个位置,这确实有意义,因为使用了优先级队列,但随后的那些并没有按照我想声明的自定义方法进行排序。

1 个答案:

答案 0 :(得分:1)

如@Bakuriu所述,如果要按顺序使用heap获取元素,则heapq仅保留nsmallest的不变量,例如:

import pyodbc

cn = pyodbc.connect('DSN=DsnName; DRIVER ={NexusDB V3.10 Driver }; DATABASE =db; 
UID=usr123;PWD=pass123')

cn.close()

输出

import heapq


class TreeNode:
    def __init__(self, f):
        self.f = f

    def __repr__(self):
        return 'f: {}'.format(self.f)

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


class Frontier:
    def __init__(self):
        self.frontier = []

    def insert(self, node):
        if isinstance(node, TreeNode):
            heapq.heappush(self.frontier, (node.f, node))
        else:
            print("Error. It is not a node.")

    def __len__(self):
        return len(self.frontier)


t = Frontier()

for n in [TreeNode(141.09530289033592), TreeNode(484.8315227978057), TreeNode(390.0514031446352)]:
    t.insert(n)

print(heapq.nsmallest(len(t), t.frontier))