Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 94aedd8

Browse files
committed
Added test for BFS
1 parent 5e244fc commit 94aedd8

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

tests/test_search.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import pytest
2+
from search import *
3+
4+
class Graph(Problem):
5+
6+
"""
7+
Graph class to test uninformed search algorithms which work on graphs with path costs.
8+
"""
9+
10+
def __init__(self, initial, goal=None, paths={}, bidirectional = False):
11+
"""
12+
The constructor takes as input the initial state, list of goal states and a dictionary representing a list of tuples which contiains the action and path cost
13+
"""
14+
#Make a dictionary of actions
15+
action_dict = {}
16+
for state in paths.keys():
17+
action_dict[state] = {}
18+
for next_state, path_cost in paths[state]:
19+
action_dict[state][next_state] = path_cost
20+
if bidirectional:
21+
if next_state not in action_dict.keys():
22+
action_dict[next_state]={}
23+
action_dict[next_state][state] = path_cost
24+
25+
update(self, initial=initial, goal=goal, action_dict=action_dict)
26+
27+
def actions(self, state):
28+
"""
29+
returns the possible actions to take as a list of strings representing the state that action leads to
30+
"""
31+
return [ action for action in self.action_dict[state] ]
32+
33+
def result(self, state, action):
34+
"""
35+
Return the state that results from executing the given action
36+
"""
37+
#Make sure the action is in actions(state)
38+
assert is_in(action, self.actions(state))
39+
return action
40+
41+
def goal_test(self, state):
42+
"""
43+
Return True if the state is a goal.
44+
"""
45+
return is_in(state, self.goal)
46+
47+
def path_cost(self, c, state1, action, state2):
48+
"""Return the cost of a solution path that arrives at state2 from
49+
state1 via action, assuming cost c to get up to state1. If the problem
50+
is such that the path doesn't matter, this function will only look at
51+
state2. If the path does matter, it will consider c and maybe state1
52+
and action. The default method costs 1 for every step in the path."""
53+
return c + self.action_dict[state1][state2]
54+
55+
Fig[3, 12] = Graph('A', ['G'], {'A':[('B', 1), ('C', 1)],
56+
'B':[('D', 1), ('E', 1)],
57+
'C':[('F', 1), ('G', 1)],
58+
'D':[],
59+
'E':[],
60+
'F':[],
61+
'G':[]})
62+
63+
def test_breadth_first_tree_search():
64+
solution_node = breadth_first_tree_search(Fig[3, 12])
65+
assert solution_node.solution() == ['C', 'G']
66+
assert [node.action for node in solution_node.path()] == [None, 'C', 'G']
67+
#Test BFS if no goal is present
68+
Fig[3, 12].goal = []
69+
assert breadth_first_tree_search(Fig[3, 12]) is None
70+
Fig[3, 12].goal = ['G']
71+
72+
if __name__ == '__main__':
73+
pytest.main()

0 commit comments

Comments
 (0)