0

I have my graph object, im trying to find a method to find a minimum for a group of nodes.

Ex. Nodes:

      input_nodes=[123,45]
      graph_nodes=[10, 76,123,45,98,456]

I run an algoritm which calculate shortest path between every node in the graph and every node in the input. I have a dictionary with all shortest paths beetwen nodes :

                {10:{123:0.56, 45:0.2}, 76:{123:0, 45:0.23}......

and so on for every graphs node. How to get only min weight which is different from zero:

Like this:

Minimum path node 10 has with node 45, Minimum path node 76 has with node 45, ...... Thatnks

boss hrustic
  • 31
  • 1
  • 4
  • Look at https://stackoverflow.com/questions/7164397/find-the-min-max-excluding-zeros-in-a-numpy-array-or-a-tuple-in-python? – Liora Haydont Feb 12 '18 at 18:29

1 Answers1

0

I assume there might be ties in the weights, i.e. one node can be equally "close" to more than one other node. The following code will include them all in a dict. The structure of the result is essentially the same as the input d, but only the minimum weight items are retained.

Update: if a node has no neighbors or only neighbors with weight 0, this node will map to a empty dict in the result.

d = {10:{123:0.56, 45:0.2}, 76:{123:0, 45:0.23}, 19:{17:0}, 20:{}}

def closest(ns):
    m = min((v for v in ns.values() if v != 0), default=-1)
    return {k: v for k, v in ns.items() if v == m}

print({k: closest(v) for k, v in d.items()})
dnswlt
  • 2,925
  • 19
  • 15