节点的平均度
average degree of a node
问题是:编写一个 Python 函数,接受 NetworkX 图和节点名称以及 returns 该节点邻居的平均度数。使用此函数为 OpenFlights US 网络中的每个节点计算此数量并取平均值。友谊悖论在这里成立吗(即最近邻居的平均度是否大于平均节点度)?
def averagedegree(G,node)
for node in G.neighbors(node)
2 * V.number_of_edges(node) / V.number_of_nodes(node) ```
and then I want to return a dict of the average degree of the neighbors BUT the average number of nodes and number of edges BOTH accept no arguments
节点的邻居的平均度数是每个邻居的度数之和除以邻居的数量。一个节点的邻居数正好是它的度数
networkx 图 G
中节点 u
的度数是 G.degree(u)
。
在python中,通过内置函数sum
.
可以很容易地求和
相关文档:
def average_degree(G, u):
return sum(G.degree(v) for v in G.neighbors(u)) / G.degree(u)
请注意,如果 u
没有邻居,此函数将引发 ZeroDivisionError
。
使用自定义图表进行测试:
from networkx import Graph
G = Graph()
G.add_edges_from([(0, 2), (0, 7), (2, 1), (2, 9), (2, 8), (1, 8), (1, 3), (9, 6), (9, 4), (9, 7), (8, 7), (8, 5), (8, 6), (7, 5), (7, 6)])
avg_degrees_dict = { u: average_degree(G,u) for u in G.nodes }
print(avg_degrees_dict)
# {0: 4.5,
# 1: 3.3333333333333335,
# 2: 3.5,
# 3: 3.0,
# 4: 4.0,
# 5: 5.0,
# 6: 4.666666666666667,
# 7: 3.2,
# 8: 3.4,
# 9: 3.25}
问题是:编写一个 Python 函数,接受 NetworkX 图和节点名称以及 returns 该节点邻居的平均度数。使用此函数为 OpenFlights US 网络中的每个节点计算此数量并取平均值。友谊悖论在这里成立吗(即最近邻居的平均度是否大于平均节点度)?
def averagedegree(G,node)
for node in G.neighbors(node)
2 * V.number_of_edges(node) / V.number_of_nodes(node) ```
and then I want to return a dict of the average degree of the neighbors BUT the average number of nodes and number of edges BOTH accept no arguments
节点的邻居的平均度数是每个邻居的度数之和除以邻居的数量。一个节点的邻居数正好是它的度数
networkx 图 G
中节点 u
的度数是 G.degree(u)
。
在python中,通过内置函数sum
.
相关文档:
def average_degree(G, u):
return sum(G.degree(v) for v in G.neighbors(u)) / G.degree(u)
请注意,如果 u
没有邻居,此函数将引发 ZeroDivisionError
。
使用自定义图表进行测试:
from networkx import Graph
G = Graph()
G.add_edges_from([(0, 2), (0, 7), (2, 1), (2, 9), (2, 8), (1, 8), (1, 3), (9, 6), (9, 4), (9, 7), (8, 7), (8, 5), (8, 6), (7, 5), (7, 6)])
avg_degrees_dict = { u: average_degree(G,u) for u in G.nodes }
print(avg_degrees_dict)
# {0: 4.5,
# 1: 3.3333333333333335,
# 2: 3.5,
# 3: 3.0,
# 4: 4.0,
# 5: 5.0,
# 6: 4.666666666666667,
# 7: 3.2,
# 8: 3.4,
# 9: 3.25}