-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.py
43 lines (31 loc) · 1.03 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
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': ['H', 'I'],
'E': ['J', 'K'],
'F': ['L', 'M'],
'G': ['N', 'O'],
'initial': ['A'],
'goal': 'L'
}
def general_search(problem, queuing_fn):
solution = []
nodes = problem['initial'][:] # weird python: to copy do slicing
while nodes:
node = nodes.pop(0)
solution.append(node)
if node == problem['goal']:
return solution
nodes = queuing_fn(problem, node, nodes)
raise Exception("No solution!")
def breadth_first_search(problem, node, nodes):
if node in problem.keys():
nodes.extend(problem[node]) # FIFO
return nodes
def depth_first_search(problem, node, nodes):
if node in problem.keys():
nodes[0:0] = problem[node] # STACK
return nodes
print "solution: " + str(general_search(graph, breadth_first_search))
print "solution: " + str(general_search(graph, depth_first_search))