来自 Java,我正在尝试在 python 中实现A* 算法,但我无法对图中 f 分数相等的顶点进行排序。我正在尝试使用 这样做heapq
,经过一些调试后,我注意到如果我想推送一个 f 分数等于堆中其他一些预先存在的顶点的顶点,那么顺序就会混乱。我现在正在考虑实施我自己的优先级队列。我想知道这是如何工作的。
行为说明如下:
>>> mylist = [1, 2, 5, 4, 3]
>>> heapq.heapify(mylist)
>>> mylist
>>> [1, 2, 3, 4, 5]
>>> heapq.heappush(mylist, 1)
>>> mylist
>>> [1, 2, 1, 4, 5, 3]
这是我为上下文实现的实际代码:
class Node(object):
def __init__(self, name, x_coordinate, y_coordinate, obstacle_flag=False):
self.name = name # possible values should only be ' ', 'A-Z', '*'
self.coordinates = (x_coordinate, y_coordinate) # this will uniquely identify the node
self.obstacle = obstacle_flag # if the name is '*' the obstacle is set to True
self.neighbors = {} # list of neighbors of this node
self.set_obstacle()
...
class Vertex(Node):
def __init__(self, name, x_coordinate, y_coordinate, obstacle_flag):
super(Vertex, self).__init__(name, x_coordinate, y_coordinate, obstacle_flag)
self.g_actual_cost = 10000
self.h_cost = 0 # the cost given by the heuristic function
self.previous_vertex = None
self.total_cost = self.g_actual_cost + self.h_cost
def __lt__(self, other):
return self.total_cost < other.total_cost
def __eq__(self, other):
if isinstance(other, Vertex):
return self.total_cost == other.total_cost
return NotImplemented