How to write a recursive function in Python?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 17:59:23

问题


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 : **

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

回答1:


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)


来源:https://stackoverflow.com/questions/54172488/how-to-write-a-recursive-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!