首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python TypeError使用两个位置参数,但给出了3个

Python TypeError使用两个位置参数,但给出了3个
EN

Stack Overflow用户
提问于 2022-10-08 21:20:12
回答 1查看 1.1K关注 0票数 0

该代码应该计算节点状态(字符位置)和最近的食物位置之间的最短曼哈顿距离。

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

注意:当调用此函数时,字符(状态位置)和食物位置位于相同的网格位置。

代码语言:javascript
复制
# 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]
EN

回答 1

Stack Overflow用户

发布于 2022-10-08 21:25:32

类的每个方法都接收其对象作为输入。这就是方法定义中"self“参数所指的内容。只要在get_manhattan_distance方法定义中添加self参数,问题就会消失。就像这样:

代码语言:javascript
复制
get_manhattan_distance(self, p, q):
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74000602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档