Objectif:我有一个图,对于每个具有二度的节点,我想删除该节点并在该节点的邻居之间添加一条边(权重 = a*b/a+b,其中 a 和 b 是有问题的节点的相邻边)。我想在每次图形更改时执行这些操作,最终得到一个没有任何节点的图形 dgree 2 。这是我附上的代码。PS:我对python(3.4.0),NetworkX 2.2非常陌生(任何其他给出类似结果的建议表示赞赏)
import networkx as nx
import matplotlib.pyplot as plt
G=nx.MultiGraph()
G.add_nodes_from([1,2,3,4,5,6,7])
G.add_edges_from([(1,2),(1,3),(2,4),(2,5),(3,6),(6,7)])
for u, v, d in G.edges(data=True):
d['weight'] = 1
def fun(G) :
L= G.degree() # L=list of all nodes of a random graph G ,and their nodes [(node, degree),(node,degree)...]
for x in L :
if x[1] == 2 : #if a certain node in L has a degree 2
adja=G.edges(x[0],data=True) #adjacent edges to the node of degree 2
weights = [d['weight'] for u,v,weight in adja] #weights=list of weights of the adjacent edges to the node x[0](the one having degree 2)
numerator=weights[0]*weights[1]
denominator=sum(weights)
var=numerator/denominator #var is the weight i would like to assign to my new edge created,it is computed like : a*b /(a+b) with a and b are weights of the adjacent edges to the node in question
tmp=list(G.neighbors(x[0])) #tmp = list of neighbors of the node to remove(neighbors in term of nodes)
G.remove_node(x[0]) #remove the node of degree 2
G.add_edge(tmp[0],tmp[1],weight=var) #add an edge between the neighbors of the node of degree 2
nx.draw(G,with_labels=True)
plt.show()
print(fun(G))