计算每个节点的邻居数量
如何判断一个节点是否重要?有多种方法可用。本节将关注其中一个指标:节点的邻居数量。
每个 NetworkX 图 G 都提供 .neighbors(n) 方法,返回节点 n 的所有邻居的迭代器。请先在 IPython Shell 中,对 Twitter 网络 T 使用该方法获取节点 1 的邻居。这将帮助您熟悉该函数的用法。随后,您的任务是编写一个函数,返回所有恰好有 m 个邻居的节点。
本练习是课程的一部分
Python 网络分析入门
练习说明
- 编写一个名为
nodes_with_m_nbrs()的函数,包含两个参数G和m,返回所有拥有m个邻居的节点。为此:- 遍历
G中的所有节点(不包括元数据)。 - 结合使用
len()与list()以及.neighbors()方法,计算图G中节点n的邻居总数。- 如果节点
n的邻居数等于m,使用.add()方法将n加入集合nodes。
- 如果节点
- 遍历完
G中的所有节点后,返回集合nodes。
- 遍历
- 使用您编写的
nodes_with_m_nbrs()函数,在图T中检索所有拥有 6 个邻居的节点。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define nodes_with_m_nbrs()
def ____:
"""
Returns all nodes in graph G that have m neighbors.
"""
nodes = set()
# Iterate over all nodes in G
for n in ____:
# Check if the number of neighbors of n matches m
if ____ == ____:
# Add the node n to the set
____
# Return the nodes with m neighbors
return nodes
# Compute and print all nodes in T that have 6 neighbors
six_nbrs = ____
print(____)