Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python优先级队列中的*搜索_Python_Search_Graph - Fatal编程技术网

Python优先级队列中的*搜索

Python优先级队列中的*搜索,python,search,graph,Python,Search,Graph,我试图用Python编写一个A*搜索来解决一个迷宫,但是我很难找到一个内置的优先级队列来解决这个问题。目前我正在使用PriorityQueue,但它不提供更改项目优先级的功能,这在算法底部的注释部分(在else if语句中)是一个问题 有没有人知道我可以在那个块中做些什么,或者内置的优先级队列会给我这个功能 def A_search(maze, start, end): expanded = 0 # use to track number of nodes expanded by the alg

我试图用Python编写一个A*搜索来解决一个迷宫,但是我很难找到一个内置的优先级队列来解决这个问题。目前我正在使用PriorityQueue,但它不提供更改项目优先级的功能,这在算法底部的注释部分(在else if语句中)是一个问题

有没有人知道我可以在那个块中做些什么,或者内置的优先级队列会给我这个功能

def A_search(maze, start, end):
expanded = 0 # use to track number of nodes expanded by the algorithm
node1 = Node(start,0)
frontier = PriorityQueue()
frontier.put((dist_to_goal(node1,end) + node1.get_cost(), node1))
visited = []
in_frontier = [] # keep track of items in frontier, PriorityQueue has no way to peek
in_frontier.append(node1)
while(True):
    if(frontier == []):
        return(None,expanded)
    curr = (frontier.get())[1]
    in_frontier.remove(curr)
    expanded += 1
    if(curr.get_loc() == end):
        return(curr,expanded)
    visited.append(curr.get_loc())
    neighbors = find_neighbors(maze, curr.get_loc())
    for neighbor in neighbors:
        node_n = Node(neighbor,node1.get_cost()+1)
        node_n.parent = curr
        if(neighbor not in visited) and (node_n not in in_frontier):
            frontier.put((dist_to_goal(node_n,end) + node1.get_cost(), node_n))
            in_frontier.append(node_n)
        # else if node_n is in frontier w/ a higher path cost then replace it w/ current

在内置库中,最接近的是


更改优先级后,您需要调用
heapq.heapify
(花费O(n)个时间,但不会改变*总体复杂度)或在O(log n)时间使用内部
heapq.\u siftdown
函数

关于优先级队列实现说明中的
heapq
模块的官方python文档中讨论了更新项目优先级: 使用这些注释,我成功地编写了自己的
PriorityQueue
实现,该实现支持添加任务并在任务存在时更新其优先级。它包括使用一个指向优先级队列中任务的
条目查找器
dict
。更新任务的优先级,只需将现有任务标记为已删除并以新优先级插入即可。 在这个实现中,您可以使用方法
add\u task

class PriorityQueue():
删除=“”
定义初始化(自):
self.pq=[]
self.entry_finder={}
self.counter=itertools.count()
def add_任务(自身、任务、优先级=0):
如果在self.entry\u finder中执行任务:
自我删除任务(任务)
计数=下一个(自我计数器)
条目=[优先级、计数、任务]
self.entry\u finder[任务]=条目
堆堆(self.pq,条目)
def删除_任务(自我,任务):
entry=self.entry\u finder.pop(任务)
条目[-1]=自删除
def pop_任务(自我):
而self.pq:
优先级、计数、任务=heapop(self.pq)
如果任务未自行删除:
del self.entry_finder[任务]
返回任务
一无所获