concept
Heuristics and A-star
A* uses g+h; on the stated finite nonnegative graph, admissible h and reopening support optimality. Greedy uses h alone. Consistency allows settling a state without reopening. Teaching interface, not a Python built-in.
Formal Syntax & Structure
artificial-intelligence syntaxartificial-intelligence
astar(graph, h, start, goal) → (cost, path) or NoneWorking Example
Example Snippetartificial-intelligence
from heapq import heappush, heappopfrom itertools import count
def astar(graph, h, start, goal): serial = count() heap = [(h[start], next(serial), 0, [start])] best = {start: 0} while heap: _, _, cost, path = heappop(heap) node = path[-1] if cost != best[node]: continue if node == goal: return cost, path for neighbor, weight in graph[node].items(): new_cost = cost + weight if neighbor not in best or new_cost < best[neighbor]: best[neighbor] = new_cost heappush(heap, (new_cost + h[neighbor], next(serial), new_cost, path + [neighbor])) return None
graph = {'S': {'A': 4, 'B': 1}, 'A': {'G': 4}, 'B': {'A': 1}, 'G': {}, 'X': {}}h = {'S': 0, 'A': 0, 'B': 5, 'G': 0, 'X': 0}print(astar(graph, h, "S", "G"))print(astar(graph, h, "X", "X"))