python编写递归函数_如何在Python中编写递归函数?

1586010002-jmsa.png

I have an undirected graph, and I want to iteratively remove each serial edge and replace it with a new edge. The weight of the new edge represents the number of spanning trees, and should be computed as follows: T_new = (1/a+b) * T_old, where a and b are the weights of the removed edges, T_new is the number of spanning trees in current iteration and T_old is the number of spanning trees in the previous iteration. This equation changes iteratively, as the graph changes, so if we have 4 iterations we will have 4 equations, each one is in terms of the previous one. We stop once the graph has no more serial edges. If the final graph is composed of 1 edge, the weight of that edge is the last T_new, and we will have a numerical value of T-old. Otherwise, we should have T_old in terms of T_new. Here is an attached image explaining what I said in case it is not well explained.

Here is the part of my code describing the problem :

** PS : I only need the part where the equation changes in every iteration, not the things to do to remove and add new edges and so on.here is an example :Ytlm3.jpg **

import networkx as nx

def fun2(G) :

L1= G.degree()

print(L1)

L= list(L1)

for x in L :

if G.degree(x[0]) == 2 : #if the adjacent edges to x[0] are serial

... do somthing(remove edges and add new one with new weight)

#T-new = 1/(a+b) T-old here the equation should change

def tau(G) : # it should return T_old which is the number of spanning trees of the initial graph

if G.number_of_edges() == 1 :

T_new = list(G.edges(data=True))[0][2]['weight']

T_old = (a+b) * t_new

else :

T_new = 1/(a+b) * tau(G)

T_old = (a+b) * t_new

return t_old

解决方案

No recursion is needed, as we change the graph as we go. Here's a solution:

import networkx as nx

G = nx.Graph()

G.add_weighted_edges_from([(0,1,5),(0,2,10),(2,3,30)])

for node in list(G.nodes()):

if G.degree(node) == 2:

neighbors = list(G.neighbors(node))

a = G.get_edge_data(neighbors[0], node)['weight']

b = G.get_edge_data(neighbors[1], node)['weight']

w = (a * b) / (a + b)

G.add_edge(neighbors[0], neighbors[1], weight=w)

G.remove_node(node)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值