Pylance提示期望有':'未找到报错位置,A*遍历代码range行报错如何解决
报错原因
你看到的Expected ":"是Python语法解析器抛出的误导性提示,实际问题并非缺少冒号:range是Python内置函数,调用时必须用括号包裹传入的参数,你写的range n属于非法语法,导致解析器无法正确识别该行末尾的冒号,才抛出了缺失冒号的错误提示。
除此之外你提供的代码还有几处逻辑问题会导致运行结果不符合预期:
- 从优先堆弹出的
v是[启发值, 节点编号]结构的列表,直接用v做字典键、数组下标都会报错,需要取v[1]才是节点编号 - 每次往优先队列添加元素不需要重新调用
heapify,使用heapq.heappush插入元素的效率更高 - 当前的路径记录逻辑只会保存遍历顺序,A*算法需要额外记录每个节点的父节点,才能回溯出正确的最短路径
解决方法
首先修改报错行的range调用语法,把for i in range n:改成for i in range(n):即可解决冒号报错的问题。
修正后符合A*逻辑的可运行参考代码如下:
import heapq def A_star_Traversal(cost, heuristic, start_point, goals): goal_set = set(goals) n = len(cost) # 记录节点父节点与到达该节点的实际开销 parent = {} g_cost = {start_point: 0} # 优先队列元素:(f值=实际开销+启发值, 节点编号) pq = [(heuristic[start_point], start_point)] visited = set() while pq: current_f, current_node = heapq.heappop(pq) if current_node in visited: continue visited.add(current_node) # 到达目标节点回溯路径 if current_node in goal_set: path = [] while current_node in parent: path.append(current_node) current_node = parent[current_node] path.append(start_point) return path[::-1] # 遍历所有邻居节点 for neighbor in range(n): if cost[current_node][neighbor] > 0 and neighbor not in visited: new_g = g_cost[current_node] + cost[current_node][neighbor] # 新路径开销更小则更新 if neighbor not in g_cost or new_g < g_cost[neighbor]: g_cost[neighbor] = new_g f = new_g + heuristic[neighbor] heapq.heappush(pq, (f, neighbor)) parent[neighbor] = current_node # 无可达路径返回空 return []
内容的提问来源于stack exchange,提问作者C S Vinayak
相关产品推荐
相关产品推荐

