diff options
Diffstat (limited to 'networkx/classes/function.py')
| -rw-r--r-- | networkx/classes/function.py | 65 |
1 files changed, 64 insertions, 1 deletions
diff --git a/networkx/classes/function.py b/networkx/classes/function.py index 378fd77a..1a99fef3 100644 --- a/networkx/classes/function.py +++ b/networkx/classes/function.py @@ -6,9 +6,9 @@ from itertools import chain import networkx as nx from networkx.utils import pairwise, not_implemented_for - from networkx.classes.graphviews import subgraph_view, reverse_view + __all__ = [ "nodes", "edges", @@ -48,6 +48,8 @@ __all__ = [ "selfloop_edges", "nodes_with_selfloops", "number_of_selfloops", + "path_weight", + "is_path", ] @@ -1234,3 +1236,64 @@ def number_of_selfloops(G): 1 """ return sum(1 for _ in nx.selfloop_edges(G)) + + +def is_path(G, path): + """Returns whether or not the specified path exists + + Parameters + ---------- + G : graph + A NetworkX graph. + + path: list + A list of node labels which defines the path to traverse + + Returns + ------- + isPath: bool + A boolean representing whether or not the path exists + + """ + for node, nbr in nx.utils.pairwise(path): + if nbr not in G[node]: + return False + return True + + +def path_weight(G, path, weight): + """Returns total cost associated with specified path and weight + + Parameters + ---------- + G : graph + A NetworkX graph. + + path: list + A list of node labels which defines the path to traverse + + weight: string + A string indicating which edge attribute to use for path cost + + Returns + ------- + cost: int + A integer representing the total cost with respect to the + specified weight of the specified path + + Raises + ------ + NetworkXNoPath + If the specified edge does not exist. + """ + multigraph = G.is_multigraph() + cost = 0 + + if not nx.is_path(G, path): + raise nx.NetworkXNoPath("path does not exist") + for node, nbr in nx.utils.pairwise(path): + if multigraph: + cost += min([v[weight] for v in G[node][nbr].values()]) + else: + cost += G[node][nbr][weight] + return cost |
