Networkx: Use common function for edge weight calculation

北城以北 提交于 2020-01-13 21:51:47

问题


Suppose I have a function euc_2d(graph, n1, n2) that calculates the euclidean distance between two nodes of the same graph. Each nodes has a given pos=(x,y) which is assigned on graph creation.

NetworkX provides a function to get the total weight of all edges of a graph namely graph.size(weight='weight'). The problem with this method is that it assumes that whenever I add an edge I should explicitly assign the appropriate edge weight like graph.add_edge(u,v,weight=?) using a lambda function for example.

However this is very inconvenient (and verbose) since I keep adding and removing edges in the graph all the time.

So, is there a pythonic way I can tell NetworkX to transparently use the euc_2d() whenever I ask the total weight of the graph?


回答1:


Neither graph.size nor graph.add_edge uses a function to evaluate the weight, they just store values with a given key. To make it easier to work with, just define a function to add an edge with the appropriate weight:

def add_euc2d_edge(graph, u, v):
    graph.add_edge(u, v, weight=euc_2d(graph, u, v))


来源:https://stackoverflow.com/questions/17370507/networkx-use-common-function-for-edge-weight-calculation

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