summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSultan Orazbayev <contact@econpoint.com>2022-12-20 22:39:54 +0600
committerGitHub <noreply@github.com>2022-12-20 11:39:54 -0500
commitb15b5168d5648e4e33b62b7a316b0d7886f60dcf (patch)
treef486631c24cc61319a81c7f09b6197b13aefb9bc
parentbbc8dd7e74c9417247009210872d30b5fbd59f48 (diff)
downloadnetworkx-b15b5168d5648e4e33b62b7a316b0d7886f60dcf.tar.gz
Update simple_paths.py: consistent behaviour for `is_simple_path` when path contains nodes not in the graph. (#6272)
* Update simple_paths.py Current version of `is_simple_path` fails with `KeyError` if the first element of the node list is not in the graph. * Update simple_paths.py * Update simple_paths.py Simplify the test condition. Checking for a single node in the list can be combined with checking for duplicates in the list without meaningful efficiency loss. * Update test_simple_paths.py Add the case when the start of the path is a node not in the graph. * Update simple_paths.py * Update simple_paths.py * Update simple_paths.py * Update simple_paths.py * Update simple_paths.py Still need to check the special case of a list with 1 item.
-rw-r--r--networkx/algorithms/simple_paths.py16
-rw-r--r--networkx/algorithms/tests/test_simple_paths.py4
2 files changed, 17 insertions, 3 deletions
diff --git a/networkx/algorithms/simple_paths.py b/networkx/algorithms/simple_paths.py
index d6baa23b..d81d2345 100644
--- a/networkx/algorithms/simple_paths.py
+++ b/networkx/algorithms/simple_paths.py
@@ -72,13 +72,23 @@ def is_simple_path(G, nodes):
# NetworkXPointlessConcept here.
if len(nodes) == 0:
return False
+
# If the list is a single node, just check that the node is actually
# in the graph.
if len(nodes) == 1:
return nodes[0] in G
- # Test that no node appears more than once, and that each
- # adjacent pair of nodes is adjacent.
- return len(set(nodes)) == len(nodes) and all(v in G[u] for u, v in pairwise(nodes))
+
+ # check that all nodes in the list are in the graph, if at least one
+ # is not in the graph, then this is not a simple path
+ if not all(n in G for n in nodes):
+ return False
+
+ # If the list contains repeated nodes, then it's not a simple path
+ if len(set(nodes)) != len(nodes):
+ return False
+
+ # Test that each adjacent pair of nodes is adjacent.
+ return all(v in G[u] for u, v in pairwise(nodes))
def all_simple_paths(G, source, target, cutoff=None):
diff --git a/networkx/algorithms/tests/test_simple_paths.py b/networkx/algorithms/tests/test_simple_paths.py
index 08348b98..c2d4c008 100644
--- a/networkx/algorithms/tests/test_simple_paths.py
+++ b/networkx/algorithms/tests/test_simple_paths.py
@@ -58,6 +58,10 @@ class TestIsSimplePath:
G = nx.path_graph(2)
assert not nx.is_simple_path(G, [0, 2])
+ def test_missing_starting_node(self):
+ G = nx.path_graph(2)
+ assert not nx.is_simple_path(G, [2, 0])
+
def test_directed_path(self):
G = nx.DiGraph([(0, 1), (1, 2)])
assert nx.is_simple_path(G, [0, 1, 2])