0% found this document useful (0 votes)
40 views

AI Journal TIT2324007

This practical journal submission summarizes Supreet Sadashiv Bhuvanagiri's work on artificial intelligence practicals at SIES College of Arts, Science and Commerce during the 2023-2024 academic year. It includes 6 practical coding exercises implementing algorithms such as depth-first search, breadth-first search, N-queens problem, Tower of Hanoi, alpha-beta pruning, and A* search. The submission is certified by the faculty-in-charge and internal/external examiners.

Uploaded by

Supreet Sadashiv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

AI Journal TIT2324007

This practical journal submission summarizes Supreet Sadashiv Bhuvanagiri's work on artificial intelligence practicals at SIES College of Arts, Science and Commerce during the 2023-2024 academic year. It includes 6 practical coding exercises implementing algorithms such as depth-first search, breadth-first search, N-queens problem, Tower of Hanoi, alpha-beta pruning, and A* search. The submission is certified by the faculty-in-charge and internal/external examiners.

Uploaded by

Supreet Sadashiv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

SIES COLLEGE OF ARTS, SCIENCE &

COMMERCE(AUTONOMOUS)
SION(W), MUMBAI-22

DEPARTMENT OF INFORMATION TECHNOLOGY

TY BSc (IT), SEMESTER V

Practical Journal
for the subject
Artificial Intelligence

Submitted by
Supreet Sadashiv Bhuvanagiri
TIT2324007

for the academic


year 2023-24
SIES College of Arts, Science and Commerce (Autonomous)
Sion (W), Mumbai – 400 022.

Department of Information Technology

CERTIFICATE

This is to certify that Mr. Supreet Sadashiv Bhuvanagiri of

TYBSc [Information Technology], Semester V, Seat No TIT2324007 has successfully

completed the practicals and submitted it online in Microsoft Teams for the subject of

ARTIFICIAL INTELLIGENCE as a partial fulfilment of the degree BSc (IT) during the academic

year 2023-2024.

Faculty-in-charge Internal Examiner


Archana Jadhav Archana Jadhav

External Examiner
Date: College Seal
Practical No. 1

1. Write a code to implement depth first search algorithm


CODE:
graph1 = {
'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 dfs(graph,node,visited):
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph,n,visited)
return visited
visited = dfs(graph1,'A',[])
print(visited)

OUTPUT:
Practical No. 2

1. Write a code 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 neighbour in neighbours:
if neighbour not in visited:
queue.append(neighbour)
visited.add(neighbour)
levels[neighbour]=levels[node]+1
print(levels)
return visited
print(str(bfs('A')))

def bfs_paths(graph,start,goal):
queue = [(start,[start])]
while queue:
(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_paths(graph,'A','F'))
print("BFS path:",result)
# For Finding the Shortest Path
def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None
result1 = shortest_path(graph,'A','F')
print("Shortest Path : ",result1)

OUTPUT:
Practical No. 3

1. Write a program to stimulate 4 – queen / N – queen problem.


CODE:
class QueenChessBoard:
def init (self, size):
self.size = size
self.columns = []

def place_in_next_row(self, column):


self.columns.append(column)

def remove_in_current_row(self):
return self.columns.pop()

def is_this_column_safe_in_next_row(self, column):


row = len(self.columns)

for queen_column in self.columns:


if column == queen_column:
return False

for queen_row, queen_column in enumerate(self.columns):


if queen_column - queen_row == column - row:
return False

for queen_row, queen_column in enumerate(self.columns):


if((self.size - queen_column) - queen_row
== (self.size - 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):
board = QueenChessBoard(size)
number_of_solutions = 0
row = 0
column = 0

while True:
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
if (column == size or row == size):
if row == size:
board.display()
print()
number_of_solutions += 1
board.remove_in_current_row()
row -= 1
try:
prev_column = board.remove_in_current_row()
except IndexError:
break
row -= 1
column = 1+ prev_column
print('Number of solutions:', number_of_solutions)
n = int(input('Enter n: '))
solve_queen(n)

OUTPUT:
Practical No. 4

1. Write a program to solve Tower of Hanoi problem.


CODE:
## Tower of Hanoi
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")
##if I change the no. 3 to 4 then I'll get more no. combinations

OUTPUT:
Practical No. 5

1. Write a program to implement alpha – beta search.


CODE:
##Alpha Beta Pruning

tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
root = 0
pruned = 0

def children(branch, depth, alpha, beta):


global tree
global root
global pruned
i=0
for child in branch:
if type(child) is list:
(nalpha, nbeta) = children(child, depth + 1, alpha, beta)
if depth % 2 == 1:
beta = nalpha if nalpha < beta else beta
else:
alpha = nbeta if nbeta > alpha else alpha
branch[i] = alpha if depth % 2 == 0 else beta
i += 1
else:
if depth % 2 == 0 and alpha < child:
alpha = child
if depth % 2 == 1 and beta > child:
beta = child
if alpha >= beta:
pruned += 1
break
if depth == root:
tree = alpha if root == 0 else beta
return(alpha, beta)

def alphabeta(in_tree = tree, start = root, upper = -15, lower = 15):


global tree
global pruned
global root

(alpha, beta) = children(tree, start, upper, lower)


if name == " main ":
print("(alpha, beta) : ", alpha, beta)
print("Results : ",tree)
print("Times pruned : ", pruned)

return (alpha, beta, tree, pruned)

if name == " main ":


alphabeta(None)

OUTPUT:
Practical No. 6

1. Write a program to implement A* algorithm.


CODE:
from simpleai.search import SearchProblem, astar

GOAL = 'HELLO WORLD'


class HelloProblem(SearchProblem):
def actions(self, state):
if len(state) < len(GOAL):
return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')
else:
return [ ]

def result(self, state, action):


return state + action

def is_goal(self, state):


return state == GOAL

def heuristic(self, state):


# how far are we from the goal?
wrong = sum([1 if state[i] != GOAL[i] else 0
for i in range(len(state))])
missing = len(GOAL) - len(state)
return wrong + missing

problem = HelloProblem(initial_state='')
result = astar(problem)
print(result.state)
print(result.path())

OUTPUT:
(Before running the python code, type the following in cmd)
Practical No. 7

1. Write a program to solve water-jug problem.


CODE:
## Water jug problem
# 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]

# to mark visited states


memory = {}

# store solution path


ans = []

def get_all_states(state):
# Let the 3 jugs be called a,b,c
a = state[0]
b = state[1]
c = state[2]
if(a==6 and b==6):
ans.append(state)
return True

# 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):
#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+b<=x):
if( get_all_states((a+b, b, 0)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b, c-(x-a))) ):
ans.append(state)
return True

#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:
Practical No. 8

1. Design the stimulation of tic-tac-toe game using min-max algorithm.


CODE:
###TIC TAC TOE Game
import os
import time

board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1

Win = 1
Draw = -1
Running = 0
Stop = 1

Game = Running
Mark = 'X'

def DrawBoard():
print(" %c | %c | %c " % (board[1],board[2],board[3]))
print(" | | ")
print(" %c | %c | %c " % (board[4],board[5],board[6]))
print(" | | ")
print(" %c | %c | %c " % (board[7],board[8],board[9]))
print(" | | ")

def CheckPosition(x):
if(board[x] == ' '):
return True
else:
return False

def CheckWin():
global Game
if(board[1] == board[2] and board[2] == board[3] and board[1] != ' '):
Game = Win
elif(board[4] == board[5] and board[5] == board[6] and board[4] != ' '):
Game = Win
elif(board[7] == board[8] and board[8] == board[9] and board[7] != ' '):
Game = Win
elif(board[1] == board[4] and board[4] == board[7] and board[1] != ' '):
Game = Win
elif(board[2] == board[5] and board[5] == board[8] and board[2] != ' '):
Game = Win
elif(board[3] == board[6] and board[6] == board[9] and board[3] != ' '):
Game = Win
elif(board[1] == board[5] and board[5] == board[9] and board[5] != ' '):
Game = Win
elif(board[3] == board[5] and board[5] == board[7] and board[5] != ' '):
Game = Win
elif(board[1]!= ' ' and board[2]!= ' ' and board[3]!= ' ' and board[4]!= ' ' and board[5]
!= ' 'and board[6]!= ' ' and board[7]!= ' ' and board[8]!= ' ' and board[9] != ' '):
Game = Draw
else:
Game = Running
print("Tic-Tac-Toe
Game")
print("Player 1[X] --- Player 2 [0]\n")
print()
print("Please Wait....")
time.sleep(1)
while(Game == Running):
os.system('cls')
DrawBoard()
if(player % 2 != 0):
print("Player 1's chance")
Mark = 'X'
else:
print("Player 2's chance")
Mark = '0'
choice = int(input("Enter the position between [1-9] where you want to mark:"))
if(CheckPosition(choice)):
board[choice] = Mark
player+=1
CheckWin()

os.system('cls')
DrawBoard()
if(Game==Draw):
print("Game
Draw")
elif(Game==Win):
player-=1 if(player%2!
=0):
print("Player 1 Won!")
else:
print("Player 1 Won!")
OUTPUT:
Practical No. 9

1. Design an application to stimulate Eight Puzzle problem.


CODE:
#8 Puzzle Problem

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_])
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
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,
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))
#if you want to use the visual debugger, use this instead:
#result = astar(EigthPuzzleProblem(INITIAL), viewer=WebViewer())
for action, state in result.path():
print('Move number', action)
print(state)
OUTPUT:

*******

You might also like