Skip to content

Commit

Permalink
Merge pull request #1072 from jstnlef/min-to-take-generator
Browse files Browse the repository at this point in the history
Returning the minimum weight from a multigraph was inefficient
  • Loading branch information
hagberg committed Mar 10, 2014
2 parents 2849a7c + 2352842 commit aaf2bc0
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions networkx/algorithms/shortest_paths/weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,8 @@ def all_pairs_dijkstra_path(G, cutoff=None, weight='weight'):
weight=weight)
return paths

def bellman_ford(G, source, weight = 'weight'):

def bellman_ford(G, source, weight='weight'):
"""Compute shortest path lengths and predecessors on shortest paths
in weighted graphs.
Expand Down Expand Up @@ -552,7 +553,7 @@ def bellman_ford(G, source, weight = 'weight'):
"""
if source not in G:
raise KeyError("Node %s is not found in the graph"%source)
raise KeyError("Node %s is not found in the graph" % source)
numb_nodes = len(G)

dist = {source: 0}
Expand All @@ -563,13 +564,13 @@ def bellman_ford(G, source, weight = 'weight'):

if G.is_multigraph():
def get_weight(edge_dict):
return min([eattr.get(weight,1) for eattr in edge_dict.values()])
return min(eattr.get(weight,1) for eattr in edge_dict.values())
else:
def get_weight(edge_dict):
return edge_dict.get(weight,1)

for i in range(numb_nodes):
no_changes=True
no_changes = True
# Only need edges from nodes in dist b/c all others have dist==inf
for u, dist_u in list(dist.items()): # get all edges from nodes in dist
for v, edict in G[u].items(): # double loop handles undirected too
Expand All @@ -584,6 +585,7 @@ def get_weight(edge_dict):
raise nx.NetworkXUnbounded("Negative cost cycle detected.")
return pred, dist


def negative_edge_cycle(G, weight = 'weight'):
"""Return True if there exists a negative edge cycle anywhere in G.
Expand Down

0 comments on commit aaf2bc0

Please sign in to comment.