heapq 自定义 compareTo
heapq custom compareTo
我正在尝试定义一个自定义方法来将有序插入到 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' class 中实施以下 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>)]
它只将最低值放在第一个位置,这确实有意义,因为使用了优先级队列,但后面的不是按我想声明的自定义方法排序的。
正如@Bakuriu 提到的,heapq 仅保持 heap, if you want to obtain the elements in order use nsmallest 的不变量,例如:
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))
输出
[(141.09530289033592, f: 141.09530289033592), (390.0514031446352, f: 390.0514031446352), (484.8315227978057, f: 484.8315227978057)]
我正在尝试定义一个自定义方法来将有序插入到 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' class 中实施以下 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>)]
它只将最低值放在第一个位置,这确实有意义,因为使用了优先级队列,但后面的不是按我想声明的自定义方法排序的。
正如@Bakuriu 提到的,heapq 仅保持 heap, if you want to obtain the elements in order use nsmallest 的不变量,例如:
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))
输出
[(141.09530289033592, f: 141.09530289033592), (390.0514031446352, f: 390.0514031446352), (484.8315227978057, f: 484.8315227978057)]