AI Journal TIT2324007
AI Journal TIT2324007
COMMERCE(AUTONOMOUS)
SION(W), MUMBAI-22
Practical Journal
for the subject
Artificial Intelligence
Submitted by
Supreet Sadashiv Bhuvanagiri
TIT2324007
CERTIFICATE
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.
External Examiner
Date: College Seal
Practical No. 1
OUTPUT:
Practical No. 2
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
def remove_in_current_row(self):
return self.columns.pop()
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
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
tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
root = 0
pruned = 0
OUTPUT:
Practical No. 6
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
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]
if(a==6 and b==6):
ans.append(state)
return True
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
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
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:
*******