Repository: root-11/graph-theory

Issue:
is_connected errors if n1 has no edges
It gives a key error at https://github.com/root-11/graph-theory/blob/c46ebd333f4996b48aebaba325076e55df053e43/graph/__init__.py#L307

Discussion:

Patch:
diff --git a/graph/__init__.py b/graph/__init__.py
index cc3bb35..5ffc7a0 100644
--- a/graph/__init__.py
+++ b/graph/__init__.py
@@ -298,19 +298,20 @@ class BasicGraph(object):
     @lru_cache(maxsize=128)
     def is_connected(self, n1, n2):
         """ helper determining if two nodes are connected using BFS. """
-        q = [n1]
-        visited = set()
-        while q:
-            n = q.pop(0)
-            if n not in visited:
-                visited.add(n)
-            for c in self._edges[n]:
-                if c == n2:
-                    return True  # <-- Exit if connected.
-                if c in visited:
-                    continue
-                else:
-                    q.append(c)
+        if n1 in self._edges:
+            q = [n1]
+            visited = set()
+            while q:
+                n = q.pop(0)
+                if n not in visited:
+                    visited.add(n)
+                for c in self._edges[n]:
+                    if c == n2:
+                        return True  # <-- Exit if connected.
+                    if c in visited:
+                        continue
+                    else:
+                        q.append(c)
         return False  # <-- Exit if not connected.
 
 


Test patch:
diff --git a/tests/test_basics.py b/tests/test_basics.py
index bc743c0..cd10dae 100644
--- a/tests/test_basics.py
+++ b/tests/test_basics.py
@@ -270,4 +270,24 @@ def test_is_not_cyclic():
 
 def test_is_really_cyclic():
     g = Graph(from_list=[(1, 1, 1), (2, 2, 1)])  # two loops onto themselves.
-    assert g.has_cycles()
\ No newline at end of file
+    assert g.has_cycles()
+
+
+def test_no_edge_connected():
+    g = Graph()
+    g.add_node(4)
+    g.add_node(5)
+    assert g.is_connected(4, 5) == False
+
+
+def test_edge_connected():
+    g = Graph()
+    g.add_edge(4, 5)
+    assert g.is_connected(4, 5) == True
+
+
+def test_edge_not_connected():
+    g = Graph()
+    g.add_edge(3, 4)
+    g.add_edge(5, 4)
+    assert g.is_connected(3, 5) == False