Certificate: MSG-SGKM College Arts, Science and Commerce
Certificate: MSG-SGKM College Arts, Science and Commerce
Certificate: MSG-SGKM College Arts, Science and Commerce
MSG-SGKM COLLEGE ARTS, SCIENCE AND COMMERCE
Tilak Road Ghatkopar(E),Mumbai 400 077,
2020-2021
Certificate
This is to certify that Mr. Saurabh R Singh.
______________________ _________________________
Internal Examiner External Examiner
_____________________
Co-Ordinator Stamp
PRACTICAL DATE TOPIC NAME SIGNATURE
NO.
3
4
Practical 02
AIM:-
Write a program to implement breadth first search algorithm.
Code:
graph={'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])
}
def bfs(start):
queue = [start]
levels={}
levels[start]=0
visited = set(start)
while queue:
node = queue.pop(0)
neighbours=graph[node]
for neighbor in neighbours:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
levels[neighbor]= levels[node]+1
print(levels)
return visited
print(str(bfs('A')))
def bfs_path(graph, start, goal):
queue = [(start, [start])]
while queue:
5
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next ==goal:
yield path + [next]
else:
queue.append((next, path + [next]))
result=list(bfs_path(graph, 'A', 'F'))
print(result)
Output:
6
Practical 03
Aim:-
Write a program to simulate 4-Queen / N-Queen problem
Code:
class QueenChessBoard:
def __init__(self, size):
# board has dimensions size x size
self.size = size
# columns[r] is a number c if a queen is placed at row r and column c.
# columns[r] is out of range if no queen is place in row r.
# Thus after all queens are placed, they will be at positions
# (columns[0], 0), (columns[1], 1), ... (columns[size - 1], size - 1)
self.columns = []
def remove_in_current_row(self):
return self.columns.pop()
# check column
for queen_column in self.columns:
if column == queen_column:
return False
# check diagonal
7
for queen_row, queen_column in enumerate(self.columns):
if queen_column - queen_row == column - row:
return False
return True
def display(self):
for row in range(self.size):
for column in range(self.size):
if column == self.columns[row]:
print('Q', end=' ')
else:
print('.', end=' ')
print()
def solve_queen(size):
"""Display a chessboard for each possible configuration of placing n queens
on an n x n chessboard and print the number of such configurations."""
board = QueenChessBoard(size)
number_of_solutions = 0
row = 0
column = 0
8
# iterate over rows of board
while True:
# place queen in next row
while column < size:
if board.is_this_column_safe_in_next_row(column):
board.place_in_next_row(column)
row += 1
column = 0
break
else:
column += 1
# small optimization:
# In a board that already has queens placed in all rows except
# the last, we know there can only be at most one position in
# the last row where a queen can be placed. In this case, there
# is a valid position in the last row. Thus we can backtrack two
# times to reach the second last row.
board.remove_in_current_row()
row -= 1
# now backtrack
9
try:
prev_column = board.remove_in_current_row()
except IndexError:
# all queens removed
# thus no more possible configurations
break
# try previous row again
row -= 1
# start checking at column = (1 + value of column in previous row)
column = 1 + prev_column
n = int(input('Enter n: '))
solve_queen(n)
Output:
10
Practical 04
AIM:-
Write a program to solve tower of Hanoi problem.
Code:
def moveTower(height,fromPole, toPole, withPole):
if height >=1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
moveTower(3,"A","B","C")
Output:
11
Practical 05
AIM:-
Write a program to implement alpha beta search.
Code:
tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
root = 0
pruned = 0
12
if depth == root:
tree = alpha if root == 0 else beta
return (alpha, beta)
if __name__ == "__main__":
print ("(alpha, beta): ", alpha, beta)
print ("Result: ", tree)
print ("Times pruned: ", pruned)
if __name__ == "__main__":
alphabeta(None)
Output:
13
14
Practical 06
AIM:-
Write a program for Hill climbing problem.
Code:
import math
increment = 0.1
startingPoint = [1, 1]
point1 = [1, 5]
point2 = [6, 4]
point3 = [5, 2]
point4 = [2, 1]
return d1 + d2 + d3 +d4
15
minDistance = sumOfDistances(startingPoint[0], startingPoint[1], point1[0],
point1[1],point2[0],point2[1],point3[0], point3[1], point4[0] ,point4[1])
flag = True
16
17
Practical 07
Aim:-
Write a program to solve water jug problem.
Code:
# 3 water jugs capacity -> (x,y,z) where x>y>z
# initial state (12,0,0)
# final state (6,6,0)
capacity = (12,8,5)
# Maximum capacities of 3 jugs -> x,y,z
x = capacity[0]
y = capacity[1]
z = capacity[2]
def get_all_states(state):
# Let the 3 jugs be called a,b,c
a = state[0]
b = state[1]
c = state[2]
18
# if current state is already visited earlier
if((a,b,c) in memory):
return False
memory[(a,b,c)] = 1
#empty jug a
if(a>0):
#empty a into b
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):
ans.append(state)
return True
else:
if( get_all_states((a-(y-b), y, c)) ):
ans.append(state)
return True
#empty a into c
if(a+c<=z):
if( get_all_states((0,b,a+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a-(z-c), b, z)) ):
ans.append(state)
return True
#empty jug b
if(b>0):
19
#empty b into a
if(a+b<=x):
if( get_all_states((a+b, 0, c)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b-(x-a), c)) ):
ans.append(state)
return True
#empty b into c
if(b+c<=z):
if( get_all_states((a, 0, b+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a, b-(z-c), z)) ):
ans.append(state)
return True
#empty jug c
if(c>0):
#empty c into a
if(a+c<=x):
if( get_all_states((a+c, b, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b, c-(x-a))) ):
ans.append(state)
return True
20
#empty c into b
if(b+c<=y):
if( get_all_states((a, b+c, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((a, y, c-(y-b))) ):
ans.append(state)
return True
return False
initial_state = (12,0,0)
print("Starting work...\n")
get_all_states(initial_state)
ans.reverse()
for i in ans:
print(i)
Output:
21
Practical 08
Aim:-
Design the simulation of TIC – TAC –TOE game using min-max algorithm
Code:
import os
import time
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1
########win Flags##########
Win = 1
Draw = -1
Running = 0
Stop = 1
###########################
Game = Running
Mark = 'X'
22
if(board[x] == ' '):
return True
else:
return False
23
else:
Game=Running
os.system('cls')
DrawBoard()
if(Game==Draw):
print("Game Draw")
elif(Game==Win):
player-=1
24
if(player%2!=0):
print("Player 1 Won")
else:
print("Player 2 Won")
Output:
25
Practical 09
Aim:-
Write a program to solve Missionaries and Cannibals problem.
Code:
import math
class State():
def __init__(self, cannibalLeft, missionaryLeft, boat, cannibalRight, missionaryRight):
self.cannibalLeft = cannibalLeft
self.missionaryLeft = missionaryLeft
self.boat = boat
self.cannibalRight = cannibalRight
self.missionaryRight = missionaryRight
self.parent = None
def is_goal(self):
if self.cannibalLeft == 0 and self.missionaryLeft == 0:
return True
else:
return False
def is_valid(self):
if self.missionaryLeft >= 0 and self.missionaryRight >= 0 \
and self.cannibalLeft >= 0 and self.cannibalRight >= 0 \
and (self.missionaryLeft == 0 or self.missionaryLeft >= self.cannibalLeft) \
and (self.missionaryRight == 0 or self.missionaryRight >= self.cannibalRight):
return True
else:
return False
def __eq__(self, other):
return self.cannibalLeft == other.cannibalLeft and self.missionaryLeft ==
other.missionaryLeft \
and self.boat == other.boat and self.cannibalRight == other.cannibalRight \
26
and self.missionaryRight == other.missionaryRight
def __hash__(self):
return hash((self.cannibalLeft, self.missionaryLeft, self.boat, self.cannibalRight,
self.missionaryRight))
def successors(cur_state):
children = [];
if cur_state.boat == 'left':
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft - 2, 'right',
cur_state.cannibalRight, cur_state.missionaryRight + 2)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 2, cur_state.missionaryLeft, 'right',
cur_state.cannibalRight + 2, cur_state.missionaryRight)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 1, cur_state.missionaryLeft - 1, 'right',
cur_state.cannibalRight + 1, cur_state.missionaryRight + 1)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft - 1, 'right',
cur_state.cannibalRight, cur_state.missionaryRight + 1)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 1, cur_state.missionaryLeft, 'right',
cur_state.cannibalRight + 1, cur_state.missionaryRight)
if new_state.is_valid():
new_state.parent = cur_state
27
children.append(new_state)
else:
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft + 2, 'left',
cur_state.cannibalRight, cur_state.missionaryRight - 2)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 2, cur_state.missionaryLeft, 'left',
cur_state.cannibalRight - 2, cur_state.missionaryRight)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 1, cur_state.missionaryLeft + 1, 'left',
cur_state.cannibalRight - 1, cur_state.missionaryRight - 1)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft + 1, 'left',
cur_state.cannibalRight, cur_state.missionaryRight - 1)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 1, cur_state.missionaryLeft, 'left',
cur_state.cannibalRight - 1, cur_state.missionaryRight)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
return children
def breadth_first_search():
initial_state = State(3,3,'left',0,0)
28
if initial_state.is_goal():
return initial_state
frontier = list()
explored = set()
frontier.append(initial_state)
while frontier:
state = frontier.pop(0)
if state.is_goal():
return state
explored.add(state)
children = successors(state)
for child in children:
if (child not in explored) or (child not in frontier):
frontier.append(child)
return None
def print_solution(solution):
path = []
path.append(solution)
parent = solution.parent
while parent:
path.append(parent)
parent = parent.parent
for t in range(len(path)):
state = path[len(path) - t - 1]
print ("(" + str(state.cannibalLeft) + "," + str(state.missionaryLeft) \
+ "," + state.boat + "," + str(state.cannibalRight) + "," + \
str(state.missionaryRight) + ")")
def main():
solution = breadth_first_search()
print ("Missionaries and Cannibals solution:")
29
print ("(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)")
print_solution(solution)
if __name__ == "__main__":
main()
Output:
30
Practical 10
AIM:-
Design an application to simulate number puzzle problem.
Code:
‘’’
8 puzzle problem, a smaller version of the fifteen puzzle:
States are defined as string representations of the pieces on the puzzle.
Actions denote what piece will be moved to the empty space.
States must allways be inmutable. We will use strings, but internally most of
the time we will convert those strings to lists, which are easier to handle.
For example, the state (string):
‘1-2-3
4-5-6
7-8-e’
will become (in lists):
[[‘1’, ‘2’, ‘3’],
[‘4’, ‘5’, ‘6’],
[‘7’, ‘8’, ‘e’]]
‘‘‘
from __future__ import print_function
from simpleai.search import astar, SearchProblem
from simpleai.search.viewers import WebViewer
GOAL = '''1-2-3
4-5-6
7-8-e'''
INITIAL = '''4-1-2
7-e-3
8-5-6'''
def list_to_string(list_):
return '\n'.join(['-'.join(row) for row in list_])
31
def string_to_list(string_):
return [row.split('-') for row in string_.split('\n')]
def find_location(rows, element_to_find):
'''Find the location of a piece in the puzzle.
Returns a tuple: row, column'''
for ir, row in enumerate(rows):
for ic, element in enumerate(row):
if element == element_to_find:
return ir, ic
# we create a cache for the goal position of each piece, so we don't have to
# recalculate them every time
goal_positions = {}
rows_goal = string_to_list(GOAL)
for number in '12345678e':
goal_positions[number] = find_location(rows_goal, number)
class EigthPuzzleProblem(SearchProblem):
def actions(self, state):
'''Returns a list of the pieces we can move to the empty space.'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actions.append(rows[row_e + 1][col_e])
if col_e > 0:
actions.append(rows[row_e][col_e - 1])
if col_e < 2:
actions.append(rows[row_e][col_e + 1])
return actions
32
def result(self, state, action):
'''Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move)
'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
row_n, col_n = find_location(rows, action)
rows[row_e][col_e], rows[row_n][col_n] = rows[row_n][col_n], rows[row_e][col_e]
return list_to_string(rows)
def is_goal(self, state):
'''Returns true if a state is the goal state.'''
return state == GOAL
def cost(self, state1, action, state2):
'''Returns the cost of performing an action. No useful on this problem, i
but needed.
'''
return 1
def heuristic(self, state):
'''Returns an *estimation* of the distance from a state to the goal.
We are using the manhattan distance.
'''
rows = string_to_list(state)
distance = 0
for number in '12345678e':
row_n, col_n = find_location(rows, number)
row_n_goal, col_n_goal = goal_positions[number]
distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal)
return distance
result = astar(EigthPuzzleProblem(INITIAL))
for action, state in result.path():
33
print('Move number', action)
print(state)
Output:
34