此代码用于计算节点状态(字符位置(与最近食物位置之间的最短曼哈顿距离。
state = ((x, y), ("some status"))
food_coords = [(x, y), (x, y), (x, y)]
注意:(x,y(是网格中的一些坐标
但是,当get_manhattan_distance(pos, food_pos)
执行时,我会得到以下错误:TypeError: GridProblem.get_manhattan_distance() takes 2 positional arguments but 3 were given
注意:当调用此函数时,字符(状态位置(和食物位置位于同一网格位置。
# helper function to calculate the manhattan distance
def get_manhattan_distance(p, q):
distance = 0
for p_i,q_i in zip(p,q):
distance += abs(p_i - q_i)
return distance
# heuristic = Manhattan distance
def h(self, node):
if self.is_goal(node.state):
return 0
pos = node.state[0] #current position (x, y)
x_coord = node.state[0][0]
y_coord = node.state[0][1]
distances = []
for food_pos in self.food_coords:
print('pos=',pos)
print('food_pos=',pos)
distances.append(self.get_manhattan_distance(pos, food_pos))
distances.sort()
return distances[0]
类的每个方法都接收其对象作为输入。这就是";自我;方法定义中的参数引用。只需将self-parameter添加到get_manhattan_distance方法定义中,问题就会解决。像这样:
get_manhattan_distance(self, p, q):