This repository has been archived by the owner on Jul 30, 2024. It is now read-only.
forked from slgraff/edx-mitx-6.00.1x
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec13-treeSearch.py
381 lines (323 loc) · 9.69 KB
/
lec13-treeSearch.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# lec13-treeSearch.py
#
# Lecture 13 - Trees
#
# edX MITx 6.00.1x
# Introduction to Computer Science and Programming Using Python
# Trees are useful for storing data that has a hierarchical aspect
### decision trees and tree search
### first version is just a binary tree
class binaryTree(object):
def __init__(self, value):
self.value = value
self.leftBranch = None
self.rightBranch = None
self.parent = None
def setLeftBranch(self, node):
self.leftBranch = node
def setRightBranch(self, node):
self.rightBranch = node
def setParent(self, parent):
self.parent = parent
def getValue(self):
return self.value
def getLeftBranch(self):
return self.leftBranch
def getRightBranch(self):
return self.rightBranch
def getParent(self):
return self.parent
def __str__(self):
return self.value
# Depth First Search
def DFSBinary(root, fcn):
queue = [root]
while len(queue) > 0:
print 'at node ' + str(queue[0].getValue())
if fcn(queue[0]):
return True
else:
temp = queue.pop(0)
if temp.getRightBranch():
queue.insert(0, temp.getRightBranch())
if temp.getLeftBranch():
queue.insert(0, temp.getLeftBranch())
return False
# Breadth First Search
def BFSBinary(root, fcn):
queue = [root]
while len(queue) > 0:
print 'at node ' + str(queue[0].getValue())
if fcn(queue[0]):
return True
else:
temp = queue.pop(0)
if temp.getLeftBranch():
queue.append(temp.getLeftBranch())
if temp.getRightBranch():
queue.append(temp.getRightBranch())
return False
# Depth First Search, Binary Ordered
# Nodes to left are less than node, nodes to right are greater
def DFSBinaryOrdered(root, fcn, ltFcn):
queue = [root]
while len(queue) > 0:
if fcn(queue[0]):
return True
# less than function
elif ltFcn(queue[0]):
temp = queue.pop(0)
if temp.getLeftBranch():
queue.insert(0, temp.getLeftBranch())
else:
temp = queue.pop(0)
if temp.getRightBranch():
queue.insert(0, temp.getRightBranch())
return False
n5 = binaryTree(5)
n2 = binaryTree(2)
n1 = binaryTree(1)
n4 = binaryTree(4)
n8 = binaryTree(8)
n6 = binaryTree(6)
n7 = binaryTree(7)
n3 = binaryTree(3)
n5.setLeftBranch(n2)
n2.setParent(n5)
n5.setRightBranch(n8)
n8.setParent(n5)
n2.setLeftBranch(n1)
n1.setParent(n2)
n2.setRightBranch(n4)
n4.setParent(n2)
n8.setLeftBranch(n6)
n6.setParent(n8)
n6.setRightBranch(n7)
n7.setParent(n6)
n4.setLeftBranch(n3)
n3.setParent(n4)
def find6(node):
return node.getValue() == 6
def find10(node):
return node.getValue() == 10
def find2(node):
return node.getValue() == 2
# less than 6
def lt6(node):
return node.getValue() > 6
# test examples
print 'DFS'
DFSBinary(n5, find6)
print ''
print 'BFS'
BFSBinary(n5, find6)
## if we wanted to return the path that got to the goal, would need to modify
# Depth First Search
# Returns path back to root
def DFSBinaryPath(root, fcn):
queue = [root]
while len(queue) > 0:
if fcn(queue[0]):
return TracePath(queue[0])
else:
temp = queue.pop(0)
if temp.getRightBranch():
queue.insert(0, temp.getRightBranch())
if temp.getLeftBranch():
queue.insert(0, temp.getLeftBranch())
return False
def TracePath(node):
if not node.getParent():
return [node]
else:
return [node] + TracePath(node.getParent())
print''
print 'DFS path'
pathTo6 = DFSBinaryPath(n5, find6)
print [e.getValue() for e in pathTo6]
## make a decision tree
## for efficiency should really generate on the fly, but here will build
## and then search
def buildDTree(sofar, todo):
if len(todo) == 0:
return binaryTree(sofar)
else:
withelt = buildDTree(sofar + [todo[0]], todo[1:])
withoutelt = buildDTree(sofar, todo[1:])
here = binaryTree(sofar)
here.setLeftBranch(withelt)
here.setRightBranch(withoutelt)
return here
def DFSDTree(root, valueFcn, constraintFcn):
queue = [root]
best = None
visited = 0
while len(queue) > 0:
visited += 1
if constraintFcn(queue[0].getValue()):
if best == None:
best = queue[0]
print best.getValue()
elif valueFcn(queue[0].getValue()) > valueFcn(best.getValue()):
best = queue[0]
print best.getValue()
temp = queue.pop(0)
if temp.getRightBranch():
queue.insert(0, temp.getRightBranch())
if temp.getLeftBranch():
queue.insert(0, temp.getLeftBranch())
else:
queue.pop(0)
print 'visited', visited
return best
def BFSDTree(root, valueFcn, constraintFcn):
queue = [root]
best = None
visited = 0
while len(queue) > 0:
visited += 1
if constraintFcn(queue[0].getValue()):
if best == None:
best = queue[0]
print best.getValue()
elif valueFcn(queue[0].getValue()) > valueFcn(best.getValue()):
best = queue[0]
print best.getValue()
temp = queue.pop(0)
if temp.getLeftBranch():
queue.append(temp.getLeftBranch())
if temp.getRightBranch():
queue.append(temp.getRightBranch())
else:
queue.pop(0)
print 'visited', visited
return best
a = [6,3]
b = [7,2]
c = [8,4]
d = [9,5]
treeTest = buildDTree([], [a,b,c,d])
def sumValues(lst):
vals = [e[0] for e in lst]
return sum(vals)
def sumWeights(lst):
wts = [e[1] for e in lst]
return sum(wts)
def WeightsBelow10(lst):
return sumWeights(lst) <= 10
def WeightsBelow6(lst):
return sumWeights(lst) <= 6
print ''
print 'DFS decision tree'
foobar = DFSDTree(treeTest, sumValues, WeightsBelow10)
print foobar.getValue()
print ''
print 'BFS decision tree'
foobarnew = BFSDTree(treeTest, sumValues, WeightsBelow10)
print foobarnew.getValue()
def DFSDTreeGoodEnough(root, valueFcn, constraintFcn, stopFcn):
stack = [root]
best = None
visited = 0
while len(stack) > 0:
visited += 1
if constraintFcn(stack[0].getValue()):
if best == None:
best = stack[0]
print best.getValue()
elif valueFcn(stack[0].getValue()) > valueFcn(best.getValue()):
best = stack[0]
print best.getValue()
if stopFcn(best.getValue()):
print 'visited', visited
return best
temp = stack.pop(0)
if temp.getRightBranch():
stack.insert(0, temp.getRightBranch())
if temp.getLeftBranch():
stack.insert(0, temp.getLeftBranch())
else:
stack.pop(0)
print 'visited', visited
return best
def BFSDTreeGoodEnough(root, valueFcn, constraintFcn, stopFcn):
queue = [root]
best = None
visited = 0
while len(queue) > 0:
visited += 1
if constraintFcn(queue[0].getValue()):
if best == None:
best = queue[0]
print best.getValue()
elif valueFcn(queue[0].getValue()) > valueFcn(best.getValue()):
best = queue[0]
print best.getValue()
if stopFcn(best.getValue()):
print 'visited', visited
return best
temp = queue.pop(0)
if temp.getLeftBranch():
queue.append(temp.getLeftBranch())
if temp.getRightBranch():
queue.append(temp.getRightBranch())
else:
queue.pop(0)
print 'visited', visited
return best
def atLeast15(lst):
return sumValues(lst) >= 15
print ''
print 'DFS decision tree good enough'
foobar = DFSDTreeGoodEnough(treeTest, sumValues, WeightsBelow10,
atLeast15)
print foobar.getValue()
print ''
print 'BFS decision tree good enough'
foobarnew = BFSDTreeGoodEnough(treeTest, sumValues, WeightsBelow10,
atLeast15)
print foobarnew.getValue()
def DTImplicit(toConsider, avail):
if toConsider == [] or avail == 0:
result = (0, ())
elif toConsider[0][1] > avail:
result = DTImplicit(toConsider[1:], avail)
else:
nextItem = toConsider[0]
withVal, withToTake = DTImplicit(toConsider[1:], avail - nextItem[1])
withVal += nextItem[0]
withoutVal, withoutToTake = DTImplicit(toConsider[1:], avail)
if withVal > withoutVal:
result = (withVal, withToTake + (nextItem,))
else:
result = (withoutVal, withoutToTake)
return result
stuff = [a,b,c,d]
val, taken = DTImplicit(stuff, 10)
print ''
print 'implicit decision search'
print 'value of stuff'
print val
print 'actual stuff'
print taken
def DFSBinaryNoLoop(root, fcn):
queue = [root]
seen = []
while len(queue) > 0:
print 'at node ' + str(queue[0].getValue())
if fcn(queue[0]):
return True
else:
temp = queue.pop(0)
seen.append(temp)
if temp.getRightBranch():
if not temp.getRightBranch() in seen:
queue.insert(0, temp.getRightBranch())
if temp.getLeftBranch():
if not temp.getLeftBranch() in seen:
queue.insert(0, temp.getLeftBranch())
return False
##comment out
n3.setLeftBranch(n5)
n5.setParent(n3)
# run DFSBinary(n5, find6)