用 Python 为 Astar 程序编写代码,以找到城市之间的最短路径。得到上述错误,我完全不知所措。在几个 .py 文件之间拉取,以下是相关部分:
来自 asdriver.py -添加了完整的 asdriver
import adata # Map data
import astar # A* class
import sys
# Default start, goal cities
defaultcities = ('Yakima, WA', 'Tampa, FL')
def printnode(n):
print n.toString()
adata.input()
startcity = raw_input("Start city [{0}]: ".format(defaultcities[0])).strip()
if startcity == '': startcity = defaultcities[0]
if startcity not in adata.cities:
print "City not recognized"
sys.exit(0)
goalcity = raw_input("Goal city [{0}]: ".format(defaultcities[1])).strip()
if goalcity == '': goalcity = defaultcities[1]
if goalcity not in adata.cities:
print "City not recognized"
sys.exit(0)
dbg = raw_input("Debug Options: [none]").strip()
findpath = astar.AS(startcity, goalcity, printnode)
ans = findpath.astar_run(printnode, dbg)
if not ans:
print "No answer"
else:
print "Final Path:"
print ans.toString()
来自 astar.py
import adata
class AS:
def __init__(self, startcity, goalcity, tracefunc):
self.startcity = startcity
self.goalcity = goalcity
self.tracefunc = tracefunc
self.openlist = [Node([startcity])]
self.closedlist = []
def heuristic(self, printnode, start, end):
raise NotImplementedError
def astar_run(self, startcity, endcity, dbg = ""):
while self.openlist:
citystep = min(self.openlist, key = lambda o:o.g + o.h)
if citystep == self.goalcity:
path = []
while citystep.parent:
path.append(citystep)
citystep = citystep.parent
path.append(citystep)
return path[::-1]
self.openlist.remove(citystep)
self.closedlist.append(citystep)
for printnode in self.openlist: #was self.tracefunc
if printnode in self.closedset:
continue
elif printnode in self.openset:
newG = citystep.g + citystep.cost(printnode)
if printnode.g > newG:
printnode.g = newG
printnode.parent = citystep
else:
printnode.g = citystep.g + citystep.cost(printnode)
printnode.h = self.heuristic(printnode, start, end)
printnode.parent = citystep
self.openset.add(printnode)
return self
class Node:
def __init__(self, path=[], f=0, g=0, h=0):
self.path = path[:]
self.f = f
self.g = g
self.h = h
self.parent = None
def toString(self):
s = 'f=%d g=%d h=%d ' % (self.f, self.g, self.h)
for city in self.path:
s = s + ' ' + city
return s
def cost(self):
raise NotImplementedError
'
完整的初学者,所以任何帮助将不胜感激。
提前致谢!!!