[英]average degree of a node
问题是:编写一个 Python function 接受 NetworkX 图和节点名称并返回该节点邻居的平均度数。 使用此 function 计算 OpenFlights 美国网络中每个节点的数量并取平均值。 友谊悖论在这里成立吗(即最近邻居的平均度数是否大于平均节点度数)?
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 Graph G
中节点u
的度数为G.degree(u)
。
在 python 中,可以使用内置的 function 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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.