bipartite 关键字
在视频中,Eric 向您介绍了 'bipartite' 关键字。该关键字是节点元数据字典的一部分,可以在添加节点时指定,也可以在节点添加后再赋值。请记住,根据定义,在二分图中,同一分区内的节点之间不能相连。
本题中,您将编写一个函数,用于返回二分图中给定分区的所有节点。在本例里,您将使用的 GitHub 二分图包含的相关分区是 'projects' 和 'users'。
本练习是课程的一部分
Python 网络分析中级
练习说明
- 编写名为
get_nodes_from_partition()的函数,接受两个参数——二分图G和G的某个partition——并仅返回该partition中的节点。- 使用
for循环遍历G的所有节点(不包含元数据)。 - 访问当前节点元数据字典中的
'bipartite'关键字。若其等于partition,将当前节点追加到列表nodes。
- 使用
- 使用
get_nodes_from_partition()函数配合len()函数:- 打印
G的'projects'分区中的节点数量。 - 打印
G的'users'分区中的节点数量。
- 打印
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define get_nodes_from_partition()
def ____:
# Initialize an empty list for nodes to be returned
nodes = []
# Iterate over each node in the graph G
for n in ____:
# Check that the node belongs to the particular partition
if G.nodes[n]['____'] == ____:
# If so, append it to the list of nodes
____
return nodes
# Print the number of nodes in the 'projects' partition
print(____(get_nodes_from_partition(____, '____')))
# Print the number of nodes in the 'users' partition
print(____(____))