-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm.py
More file actions
93 lines (74 loc) · 2.69 KB
/
algorithm.py
File metadata and controls
93 lines (74 loc) · 2.69 KB
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
from time import sleep
class Node:
def __init__(self, root, action, state):
self.state = state
self.root = root
self.action = action
class DFS:
def __init__(self):
self.stack = []
def is_empty(self):
"""
check if the stack is empty
"""
return len(self.stack) == 0
def add(self, node):
"""
Add a new item to to end of a stack
"""
self.stack.append(node)
def remove(self):
"""
Remove from the end of a stack, using the
Last in first out(LIFO)
"""
node = self.stack[-1] # remove the last node from the stack
self.stack = self.stack[:-1] # update the stack
return node
def contains(self, state, iterable):
"""
Check if an item exists in a listjg
"""
for item in iterable:
if item.state == state:
return True
return False
def algorithm(self, start, goal, callback):
"""
This algorithm go through all the possible nodes
that can be explored in a graph and returns the optimum
path used to reach the goal
"""
explored = list() # maintain all the nodes that have been visitted
count = 0
begin = start
start_node = Node(root=None, action=None, state=begin)
self.add(start_node) # add start node to the our stack
while not self.is_empty():
node = self.remove()
count += 1 # keep a count of the number of visited nodes
if node and node.state == goal: # go here if the current node is our goal
explored = []
# backtracking to find the path used to get to the goal
# an optimum path
while node.root:
explored.append(node.state)
node = node.root
break
n = callback(node.state)
# use the current that's being exployed and expand it to get
# it's neighbouring nodes for exploring
for a, new_state in n:
if not self.contains(new_state,
self.stack) and not self.contains(
new_state, explored):
child_node = Node(root=node, action=a, state=new_state)
self.add(child_node)
explored.append(node)
return count, list(reversed(explored))
class BFS(DFS):
def remove(self):
node = self.stack[
0] # Removing an item from the list at the zero index (FIRST IN FIRST OUT(FIFO) or queue)
self.stack = self.stack[1:]
return node