Python&NumPy:使用条件(使用特定的数据类型)搜索最小值

2024-09-30 22:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python开发A*路径查找算法,并使用以下数据类型将数据很好地压缩到2D NumPy数组中:

numpy.dtype([
  ('open', bool),
  ('closed', bool),
  ('parent', object),
  ('g', int),
  ('f', int)
])

pseudo-code from Wikipedia's "A* search algorithm" entry之后,我需要解释一下:

^{pr2}$

此位将为我提供最低“f”值的索引(工作数组定义为pathArray):

numpy.unravel_index(numpy.argmin(pathArray['f']), pathArray['f'].shape)

…此位将找到“open”为真的所有索引:

numpy.where(pathArray['open'])

如何将这些条件一起使用,在“open”为真的情况下找到最低的“f”值?在


Tags: 数据路径numpy算法object数组openparent
2条回答

与其在pathArray['f']上使用np.argmin,不如在pathArray[pathArray['open']]['f']上使用它。当然,您必须调整结果,以便可以将其与pathArray['f']一起使用。。。在


另一种方法是沿着'f'字段对pathArray排序,然后找到{}为True的第一个条目。在

我对numpy不太熟悉,但我仍然“认为”使用内置函数无法做到这一点。但我还是会尽力解释。Wikipedia的意思是你需要一个priority queue这样做:

current := the node in openset having the lowest f_score[] value

您需要非常快速地执行此操作,我建议您构建一个二进制堆并将其用作优先级队列。这在python中很容易实现。This是一篇很好的文章,它解释了heaps和{}及其在python中的实现。
祝你好运

相关问题 更多 >