Skip to content

Commit 8024d2a

Browse files
author
cheung
committed
Add error-checking for not present node in graph
Also included unit tests for not present node in graph
1 parent c01447f commit 8024d2a

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

algorithms/searching/depth_first_search.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
Pseudocode: https://en.wikipedia.org/wiki/Depth-first_search
1717
"""
1818
def dfs(graph,start,path = []):
19+
if start not in graph or graph[start] == None or graph[start] == []:
20+
return None
1921
path = path + [start]
2022
for edge in graph[start]:
2123
if edge not in path:

algorithms/tests/test_searching.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,10 @@ def test_dfs(self):
8585
'G': ['C']}
8686
rv1 = depth_first_search.dfs(self.graph, "A")
8787
rv2 = depth_first_search.dfs(self.graph, "G")
88+
rv1e = depth_first_search.dfs(self.graph, "Z")
8889
self.assertEqual(rv1, ['A', 'B', 'D', 'F', 'C', 'G', 'E'])
8990
self.assertEqual(rv2, ['G', 'C', 'A', 'B', 'D', 'F', 'E'])
91+
self.assertEqual(rv1e, None)
9092
self.graph = {1:[2,3,4],
9193
2:[1,6,10],
9294
3:[1,5,10],
@@ -102,9 +104,11 @@ def test_dfs(self):
102104
rv3 = depth_first_search.dfs(self.graph,1)
103105
rv4 = depth_first_search.dfs(self.graph,5)
104106
rv5 = depth_first_search.dfs(self.graph,6)
107+
rv2e = depth_first_search.dfs(self.graph,99)
105108
self.assertEqual(rv3, [1, 2, 6, 7, 8, 9, 10, 3, 5, 12, 4, 11])
106109
self.assertEqual(rv4, [5, 3, 1, 2, 6, 7, 8, 9, 10, 12, 4, 11])
107110
self.assertEqual(rv5, [6, 2, 1, 3, 5, 10, 9, 12, 4, 11, 7, 8])
111+
self.assertEqual(rv2e, None)
108112
self.graph = {1:[2,3,4,5,6],
109113
2:[1,4,7,8,9],
110114
3:[1,10],
@@ -123,6 +127,8 @@ def test_dfs(self):
123127
rv6 = depth_first_search.dfs(self.graph,1)
124128
rv7 = depth_first_search.dfs(self.graph,10)
125129
rv8 = depth_first_search.dfs(self.graph,5)
130+
rv3e = depth_first_search.dfs(self.graph,-1)
126131
self.assertEqual(rv6, [1, 2, 4, 11, 12, 7, 8, 9, 10, 3, 5, 13, 14, 15, 6])
127132
self.assertEqual(rv7, [10, 3, 1, 2, 4, 11, 12, 7, 8, 9, 5, 13, 14, 15, 6])
128133
self.assertEqual(rv8, [5, 1, 2, 4, 11, 12, 7, 8, 9, 10, 3, 6, 15, 13, 14])
134+
self.assertEqual(rv3e, None)

0 commit comments

Comments
 (0)