I have the following python code:
import networkx as nx
def cost(i, j, d, value1, value2):
# some operation involving all these values
return cost
# graph is a networkx graph
# src, dst are integers
# cost is a callable that is passed 3 values automatically i.e. src, dst and d
# d is a dictionary of edge weights
path = nx.dijkstra_path(graph, src, dst, weight=cost)
Now I want to pass two values value1
and value2
to the cost
function.
The networkx
documentation says the weight
can be a callable that accepts exactly 3 arguments. But i need value1
and value2
for calculations. How can this be done?
Edit
The solution using functools works well. However, my function is in a class as follows:
import networkx as nx
import functools
class Myclass:
def cost(self, i, j, d, value2):
# some operation involving all these values
# also need self
# graph is a networkx graph
# src, dst are integers
# cost is a callable that is passed 3 values automatically i.e. src, dst and d
# d is a dictionary of edge weights
# path = nx.dijkstra_path(graph, src, dst, cost)
cost_partial = functools.partial(cost, self=self, value2=5)
path = nx.dijkstra_path(graph, src, dst, cost_partial)
Using this approach, nx.dijkstra_path
insists upon assigning src
to self
. Thus the interpreter complains that self
is assigned multiple values.
I need self for calculating the cost.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…