KeyError: <bound method>解析修复及CS50 Degrees项目代码无响应问题
CS50 Degrees项目问题修复指南
一、初始KeyError问题修复
你遇到的KeyError: <bound method QueueFrontier.remove of ...>错误,根源是调用队列移除方法时未加括号:
node = frontier.remove # 错误:仅赋值方法本身,未调用方法获取节点
正确写法是调用方法(加括号):
node = frontier.remove() # 正确:调用remove方法取出队列中的节点
二、修复后无输出/无限循环问题排查
修复KeyError后程序无输出且光标闪烁,核心问题有两点:
1. 探索集合explored存储对象错误
代码中explored.add(node)将Node对象存入集合,但后续判断邻居state是否已探索时,用的是state not in explored——state是演员标识(如ID或名字),和Node对象类型完全不同,这个判断永远为True,导致同一个演员节点被反复加入队列,程序陷入无限循环,永远无法抵达目标节点,自然不会打印"this happens"。
2. 节点处理顺序逻辑瑕疵
取出节点后直接将Node加入explored,未先检查该节点的state是否已被探索,可能导致重复处理。
具体修复代码
修改后的shortest_path函数如下:
def shortest_path(source, target): start = Node(state=source, parent=None, action=None) frontier = QueueFrontier() frontier.add(start) # 改为存储演员的state(ID/名字),而非Node对象 explored = set() while True: if frontier.empty(): return None node = frontier.remove() # 优先检查是否抵达目标 if node.state == target: print("this happens") actions = [] states = [] # 回溯路径:包含完整的演员链(从target到source) while node is not None: states.append(node.state) if node.action is not None: actions.append(node.action) node = node.parent # 反转路径,转为从source到target的顺序 states.reverse() actions.reverse() # 返回(电影列表, 演员列表),符合项目要求格式 return (actions, states) # 仅当该state未被探索过时,才处理其邻居 if node.state not in explored: explored.add(node.state) for action, state in neighbors_for_person(node.state): if not frontier.contains_state(state) and state not in explored: child = Node(state=state, parent=node, action=action) frontier.add(child)
额外说明
- 回溯路径时,原代码仅从parent节点开始收集,会漏掉起始的source节点,修改后改为
while node is not None,确保路径包含完整的演员链。 action对应电影信息,state对应演员信息,最终返回的元组结构符合项目要求的(电影路径, 演员路径)格式。
内容的提问来源于stack exchange,提问作者skateb2020
相关产品推荐
相关产品推荐

