【发布时间】:2020-12-25 10:39:29
【问题描述】:
我的 a* 算法的 python 实现有问题,但只有一个优势。 当我运行代码搜索具有两个损坏节点的路径时,代码会尝试比较单个节点以将其插入我的优先级队列中,但我已经定义了另一个类,这是帮助我向您解释的代码
def a_search(self, start, goal):
if start not in self.connections or goal not in self.connections:
raise Exception("Non sono stati forniti nodi validi.")
frontier = PriorityQueue()
frontier.put(PrioritizedItem(0, start))
visited_path = {}
estimated_cost = dict()
visited_path[start] = None
estimated_cost[start] = 0
while not frontier.empty():
current = frontier.get()
current = current.get_node()
if current == goal:
break
next_node: Node
for next_node in self.connection(current):
new_cost = estimated_cost[current] + self.pathweight(current, next_node)
if next_node not in estimated_cost or new_cost < estimated_cost[next_node]:
estimated_cost[next_node] = new_cost
priority = new_cost + self.euristic(next_node, goal)
frontier.put(PrioritizedItem(priority, next_node))
visited_path[next_node] = current
return frontier
这是 PrioritizedItem 类
@dataclass(order=True)
class PrioritizedItem:
priority: float
item: object = field()
def get_node(self):
return self.item
def __cmp__(self, other):
if self.priority < other.priority:
return -1
elif self.priority > other.priority:
return 1
else:
return 0
【问题讨论】:
-
__cmp__在 Python 3 中没有做任何事情 - 很久以前就被丰富的比较取代了。
标签: python python-3.x algorithm runtime-error