-
Notifications
You must be signed in to change notification settings - Fork 1
/
search.py
281 lines (217 loc) · 7.49 KB
/
search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/env python3
from functools import partial
"""
==========================
BFS - Breadth-first search
==========================
Intro: https://en.wikipedia.org/wiki/Breadth-first_search
BFS starts from the tree root, and explores all the neighbor nodes at the
present depth prior to moving on the nodes at the next depth level.
A
| \
B D - F
| | |
C G - I
| /
E
Suppose we have the tree as above, BFS starts from node `A`, and explores all
its descendant `B`, `D` before exploring the descendant of `B` and `D`.
The BFS loop sequence would be looked like this:
1) Traverse: A, seen: {'A'}, pending: ['B', 'D']
2) Traverse: B, seen: {'A', 'B'}, pending: ['D', 'C']
3) Traverse: D, seen: {'A', 'B', 'D'}, pending: ['C', 'F', 'G']
4) Traverse: C, seen: {'A', 'B', 'D', 'C'}, pending: ['F', 'G', 'E']
5) Traverse: F, seen: {'A', 'B', 'D', 'C', 'F'}, pending: ['G', 'E', 'I']
6) Traverse: G, seen: {'A', 'B', 'D', 'C', 'F', 'G'}, pending: ['E', 'I', 'E']
7) Traverse: E, seen: {'A', 'B', 'D', 'C', 'F', 'G', 'E'}, pending: ['I', 'E']
7) Traverse: I, seen: {'A', 'B', 'D', 'C', 'F', 'G', 'E', 'I'}, pending: ['E']
9) 'E' already seen, so skip it
10) pending is empty, loop finished.
==========================
DFS - Depth-first search
==========================
Intro: https://en.wikipedia.org/wiki/Depth-first_search
Let's also take the tree above as an example, the DFS loop sequence would look
like this:
1) Traverse: A, seen: {'A'}, pending: ['B', 'D']
2) Traverse: B, seen: {'A', 'B'}, pending: ['C', 'D']
3) Traverse: C, seen: {'A', 'B', 'C'}, pending: ['E', 'D']
4) Traverse: E, seen: {'A', 'B', 'C', 'E'}, pending: ['G', 'D']
5) Traverse: G, seen: {'A', 'B', 'C', 'E', 'G'}, pending: ['D', 'I', 'D']
6) Traverse: D, seen: {'A', 'B', 'C', 'E', 'G', 'D'}, pending: ['F', I', 'D']
7) Traverse: F, seen: {'A', 'B', 'C', 'E', 'G', 'D', 'F'}, pending: ['I', 'D']
8) Traverse: I, seen: {'A', 'B', 'C', 'E', 'G', 'D', 'F', 'I'}, pending: ['D']
9) 'D' already seen, so skip it
10) pending is empty, loop finished.
"""
def search_neighbor_first(tree, start_node, target):
"""
Search all the neighbor nodes first before exploring the descendants
If target is found, then return the path for the search.
Otherwise, return empty list []
:param dict tree: A dictionary represent the tree
:param start_node: The key of node to start search
:param target: The target node you need to find
"""
seen = set()
pending = [start_node]
res = []
while len(pending) > 0:
node = pending.pop(0)
if node in seen:
continue
descendant = tree[node]
for item in descendant:
if item not in seen:
# Append the descendant nodes in the last of the list
# So they would be explored later
pending.append(item)
seen.add(node)
res.append(node)
if node == target:
return res
return []
def search_descendant_first(tree, start_node, target):
"""
Search the descendant nodes first before exploring the neighbors
If target is found, then return the path for the search.
Otherwise, return empty list []
:param dict tree: A dictionary represent the tree
:param start_node: The key of node to start search
:param target: The target node you need to find
"""
seen = set()
pending = [start_node]
res = []
while len(pending) > 0:
node = pending.pop(0)
if node in seen:
continue
descendant = tree[node]
for item in descendant:
if item not in seen:
# Insert the descendant nodes in the head of the list
# So they would be explored first
pending.insert(0, item)
seen.add(node)
res.append(node)
if node == target:
return res
return []
def tranverse_neighbor_first(tree, start_node):
"""
Tranverse all the neighbor nodes first before exploring the descendants
:param dict tree: A dictionary represent the tree
:param start_node: The key of node to start tranverse
"""
seen = set()
pending = [start_node]
res = []
while len(pending) > 0:
node = pending.pop(0)
if node in seen:
continue
descendant = tree[node]
for item in descendant:
if item not in seen:
# Append the descendant nodes in the last of the list
# So they would be explored later
pending.append(item)
seen.add(node)
res.append(node)
return res
def tranverse_descendant_first(tree, start_node):
"""
Tranverse the descendant nodes first before exploring the neighbors
:param dict tree: A dictionary represent the tree
:param start_node: The key of node to start tranverse
"""
seen = set()
pending = [start_node]
res = []
while len(pending) > 0:
node = pending.pop(0)
if node in seen:
continue
descendant = tree[node]
for item in descendant:
if item not in seen:
# Insert the descendant nodes in the head of the list
# So they would be explored first
pending.insert(0, item)
seen.add(node)
res.append(node)
return res
def tranverse(func, tree, start_node):
"""
Tranverse the tree
:param dict tree: A dictionary represent the tree
:param start_node: The key of node to start tranverse
"""
return func(tree, start_node)
def print_tranverse_path(seq):
"""
Print the tranverse path
"""
for node in seq:
print('I saw: {}'.format(node))
def search(func, tree, start_node, target):
"""
Search the tree with target from start_node and return the path
:param dict tree: A dictionary represent the tree
:param start_node: The key of node to start search
:param target: The target node you need to find
"""
return func(tree, start_node, target)
def print_search_path(seq):
"""
Print the search path
"""
for idx, node in enumerate(seq):
if idx == len(seq) - 1:
print('I got you: {}'.format(node))
else:
print('I saw: {}'.format(node))
# Breadth-first tranverse
bft = partial(tranverse, tranverse_neighbor_first)
# Depth-first tranverse
dft = partial(tranverse, tranverse_descendant_first)
# Breadth-first search
bfs = partial(search, search_neighbor_first)
# Depth-first search
dfs = partial(search, search_neighbor_first)
if __name__ == '__main__':
tree = {
'A': 'B D',
'B': 'A C',
'C': 'B E',
'D': 'A F G',
'E': 'C G',
'F': 'D I',
'G': 'D E I',
'I': 'F G',
}
tree = {k: set(v.split(' ')) for k, v in tree.items()}
# Breadth-first tranverse
print('Breadth-first tranverse from "A"...')
res = bft(tree, 'A')
print_tranverse_path(res)
# Depth-first tranverse
print('Depth-first tranverse from "A"...')
res = dft(tree, 'A')
print_tranverse_path(res)
# Breadth-first tranverse
print('Breadth-first tranverse from "E"...')
res = bft(tree, 'E')
print_tranverse_path(res)
# Depth-first tranverse
print('Depth-first tranverse from "E"...')
res = dft(tree, 'E')
print_tranverse_path(res)
# Search
print('Breadth-first search from "A" to find "F"...')
res = bfs(tree, 'A', 'F')
print_search_path(res)
print('Depth-first search from "A" to find "F"...')
res = dfs(tree, 'A', 'F')
print_search_path(res)