AI Beyond Language Models · Search and Games
Maps, games and robots all need to find routes. A* always explores the most promising place next: the distance so far plus a guess of the distance left.
import heapq
# Find the shortest way to school. A* tries the most promising place first:
# distance so far + a guess of the distance left.
roads = {"home": {"park": 2, "shop": 5}, "park": {"shop": 2, "school": 6}, "shop": {"school": 2}, "school": {}}
guess = {"home": 5, "park": 4, "shop": 2, "school": 0} # straight-line distance to school
frontier = [(guess["home"], 0, "home", ["home"])]
while frontier:
estimate, cost, place, path = heapq.heappop(frontier)
if place == "school":
break
for nxt, dist in roads[place].items():
heapq.heappush(frontier, (cost + dist + guess[nxt], cost + dist, nxt, path + [nxt]))
print(path, "length", cost)frontier to decide whether the loop keeps going.place == "school" to decide which way the code goes.nxt is created with the value 'park'. dist is created with the value 2.nxt changes from 'park' to 'shop'. dist changes from 2 to 5.for nxt, dist in roads[place].items().frontier to decide whether the loop keeps going.place == "school" to decide which way the code goes.dist changes from 5 to 2.nxt changes from 'shop' to 'school'. dist changes from 2 to 6.for nxt, dist in roads[place].items().frontier to decide whether the loop keeps going.place == "school" to decide which way the code goes.dist changes from 6 to 2.for nxt, dist in roads[place].items().frontier to decide whether the loop keeps going.break.