summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorpmlpm1986 <96069104+pmlpm1986@users.noreply.github.com>2022-09-06 23:44:28 +0200
committerJarrod Millman <jarrod.millman@gmail.com>2022-09-30 09:49:50 -0700
commitf1d03e9a853d5ebd68d099684c5c67cb9b886426 (patch)
treefba708d711975af5eedd16e25ab52f0db6c0fd30
parent0956e8407fb45c9b40e90d5178126355b1199d60 (diff)
downloadnetworkx-f1d03e9a853d5ebd68d099684c5c67cb9b886426.tar.gz
Change is_path to return False when node not in G instead of raising exception (#5943)
Formerly, is_path raised a KeyError when one of the nodes in the input path was not actually in G. This PR modifies the function so that it returns False in this case instead of raising an exception.
-rw-r--r--networkx/classes/function.py7
-rw-r--r--networkx/classes/tests/test_function.py4
2 files changed, 10 insertions, 1 deletions
diff --git a/networkx/classes/function.py b/networkx/classes/function.py
index fb24105f..a0807942 100644
--- a/networkx/classes/function.py
+++ b/networkx/classes/function.py
@@ -1279,7 +1279,10 @@ def number_of_selfloops(G):
def is_path(G, path):
- """Returns whether or not the specified path exists
+ """Returns whether or not the specified path exists.
+
+ For it to return True, every node on the path must exist and
+ each consecutive pair must be connected via one or more edges.
Parameters
----------
@@ -1296,6 +1299,8 @@ def is_path(G, path):
"""
for node, nbr in nx.utils.pairwise(path):
+ if node not in G:
+ return False
if nbr not in G[node]:
return False
return True
diff --git a/networkx/classes/tests/test_function.py b/networkx/classes/tests/test_function.py
index 051d655c..df17f200 100644
--- a/networkx/classes/tests/test_function.py
+++ b/networkx/classes/tests/test_function.py
@@ -771,12 +771,16 @@ def test_pathweight():
def test_ispath():
valid_path = [1, 2, 3, 4]
invalid_path = [1, 2, 4, 3]
+ another_invalid_path = [1, 2, 3, 4, 5]
+ yet_another_invalid_path = [1, 2, 5, 3, 4]
graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
edges = [(1, 2), (2, 3), (1, 2), (3, 4)]
for graph in graphs:
graph.add_edges_from(edges)
assert nx.is_path(graph, valid_path)
assert not nx.is_path(graph, invalid_path)
+ assert not nx.is_path(graph, another_invalid_path)
+ assert not nx.is_path(graph, yet_another_invalid_path)
@pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))