如何解决a* 单边算法问题
我的 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 中不做任何事情。它很久以前就被 rich comparisons 取代了 - 每个比较运算符的单独方法,可以返回任意对象。
您告诉 dataclass
使用 order=True
为您生成比较方法。如果您不希望在比较中考虑某个字段,则可以为该字段指定 compare=False
...但是具有相同优先级和不同项目的优先级项实例将被视为相等 ,这可能会产生奇怪的副作用。
不是改变比较逻辑,处理这种事情的常用技巧是向元素添加一个递增的计数器字段,并将其用于决胜局,例如 (priority,counter_value,item)
而不是 (priority,item)
。如果您想坚持使用数据类,您可以添加一个名为 counter
或介于 priority
和 item
之间的字段。
顺便说一句,如果 PriorityQueue
是来自 queue
模块的类,您应该改用 heapq
。 queue.PriorityQueue
专门用作优先级线程间消息传递系统,它的设计决策和开销对于单线程使用没有意义。例如,它会在 get
上阻塞,而不是在没有任何东西可获取时引发异常。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。