最短路径 II
既然您已经编写了检查目标节点是否存在于邻居中的代码,接下来,您将扩展同一个函数,编写当目标节点不在邻居中的情况。
您需要编写的代码都在 else 分支中;也就是说,当 node2 不在 neighbors 中时。
本练习是课程的一部分
Python 网络分析入门
练习说明
- 使用
.add()方法,将当前节点node添加到集合visited_nodes,以记录已访问的节点。 - 将当前节点
node尚未访问过的邻居添加到queue。为此,您需要将queue的.extend()方法与列表推导式结合使用。.extend()方法会追加给定列表中的所有元素。- 列表推导式的 输出表达式 和 迭代变量 都是
n。可迭代对象 是neighbors的迭代器;条件是当n不在 已访问节点中时。
- 列表推导式的 输出表达式 和 迭代变量 都是
交互式实操练习
通过完成这段示例代码来试试这个练习。
def path_exists(G, node1, node2):
"""
This function checks whether a path exists between two nodes (node1, node2) in graph G.
"""
visited_nodes = set()
queue = [node1]
for node in queue:
neighbors = G.neighbors(node)
if node2 in neighbors:
print('Path exists between nodes {0} and {1}'.format(node1, node2))
return True
else:
# Add current node to visited nodes
____
# Add neighbors of current node that have not yet been visited
queue.extend([____ for ____ in ____ if ____ not in ____])