AI Practicals
AI Practicals
PRACTICAL NO-1
Solution:
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'])
visited.append(node)
for n in graph[node]:
dfs(graph,n, visited)
return visited
visited = dfs(graph1,'A',[])
print(visited)
Page |3
Output:
Page |4
Solution:
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]
visited = set(start)
while queue:
node = queue.pop(0)
neighbours = graph[node]
queue.append(neighbor)
visited.add(neighbor)
levels[neighbor]= levels[node]+1
return visited
queue = [(start,[start])]
while queue:
if next == goal:
else:
try:
except StopIteration:
return None
print(result) #['A','C','F']
Output:
Page |7
Practical no-2
Solution:
class QueenChessBoard:
self.size = size
self.columns = []
self.columns.append(column)
def remove_in_current_row(self):
return self.columns.pop()
row = len(self.columns)
# check column
if column == queen_column:
return False
# check diagonal
return False
return False
return True
def display(self):
if column == self.columns[row]:
else:
print()
def solve_queen(size):
configurations."""
board = QueenChessBoard(size)
number_of_solutions = 0
row = 0
Page |9
column = 0
while True:
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 row == size:
board.display()
print()
number_of_solutions += 1
# small optimization:
# the last row where a queen can be placed. In this case, there
P a g e | 10
board.remove_in_current_row()
row -= 1
# now backtrack
try:
prev_column = board.remove_in_current_row()
except IndexError:
break
row -= 1
column = 1 + prev_column
n = int(input('Enter n: '))
solve_queen(n)
P a g e | 11
Output:
P a g e | 12
Solution:
if height >=1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
moveTower(3,"A","B","C")
Output:
P a g e | 13
PRACTICAL NO.-3
Solution:
tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
root = 0
pruned = 0
global tree
global root
global pruned
i=0
if type(child) is list:
if depth % 2 == 1:
else:
i += 1
else:
P a g e | 14
alpha = child
beta = child
pruned += 1
break
if depth == root:
global tree
global pruned
global root
if __name__ == "__main__":
if __name__ == "__main__":
alphabeta(None)
P a g e | 15
Output:
P a g e | 16
Solution:
import math
increment = 0.1
startingPoint = [1, 1]
point1 = [1,5]
point2 = [6,4]
point3 = [5,2]
point4 = [2,1]
return dist
def sumOfDistances(x1, y1, px1, py1, px2, py2, px3, py3, px4, py4):
return d1 + d2 + d3 + d4
d1 = [x1, y1]
point3[0],point3[1], point4[0],point4[1] )
d1.append(d1temp)
return d1
point1[0],point1[1], point2[0],point2[1],
point3[0],point3[1], point4[0],point4[1] )
flag = True
if d1[2] == minimum:
i=1
while flag:
minDistance = minimum
i+=1
else:
flag = False
P a g e | 19
Output:
P a g e | 20
Practical no-4
Solution:
class HelloProblem(SearchProblem):
else:
return []
for i in range(len(state))])
problem = HelloProblem(initial_state='')
result = astar(problem)
print(result.state)
print(result.path())
Output:
P a g e | 22
Practical no-5
Solution:
capacity = (12,8,5)
x = capacity[0]
y = capacity[1]
z = capacity[2]
memory = {}
ans = []
def get_all_states(state):
a = state[0]
b = state[1]
c = state[2]
ans.append(state)
return True
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:
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:
P a g e | 24
ans.append(state)
return True
#empty jug b
if(b>0):
#empty b into a
if(a+b<=x):
ans.append(state)
return True
else:
ans.append(state)
return True
#empty b into c
if(b+c<=z):
ans.append(state)
return True
else:
ans.append(state)
return True
P a g e | 25
#empty jug c
if(c>0):
#empty c into a
if(a+c<=x):
ans.append(state)
return True
else:
ans.append(state)
return True
#empty c into b
if(b+c<=y):
ans.append(state)
return True
else:
ans.append(state)
return True
return False
initial_state = (12,0,0)
print("Starting work...\n")
P a g e | 26
get_all_states(initial_state)
ans.reverse()
for i in ans:
print(i)
Output:
P a g e | 27
B. Design the simulation of tic – tac – toe game using min-max algorithm.
Solution:
import os
import time
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1
########win Flags##########
Win = 1
Draw = -1
Running = 0
Stop = 1
###########################
Game = Running
Mark = 'X'
def DrawBoard():
print("___|___|___")
print("___|___|___")
P a g e | 28
print(" | | ")
def CheckPosition(x):
return True
else:
return False
def CheckWin():
global Game
Game = Win
Game = Win
Game = Win
Game = Win
Game = Win
P a g e | 29
Game=Win
Game = Win
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()
print()
print("Please Wait...")
time.sleep(1)
while(Game == Running):
os.system('cls')
DrawBoard()
if(player % 2 != 0):
P a g e | 30
Mark = 'X'
else:
Mark = 'O'
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 2 Won")
P a g e | 31
Output:
P a g e | 32
P a g e | 33
PRACTICAL No.-6
Solution:
import math
class State():
self.cannibalLeft = cannibalLeft
self.missionaryLeft = missionaryLeft
self.boat = boat
self.cannibalRight = cannibalRight
self.missionaryRight = missionaryRight
self.parent = None
def is_goal(self):
return True
else:
return False
def is_valid(self):
return True
else:
return False
def __hash__(self):
def successors(cur_state):
children = [];
if cur_state.boat == 'left':
cur_state.cannibalRight, cur_state.missionaryRight + 2)
if new_state.is_valid():
P a g e | 35
new_state.parent = cur_state
children.append(new_state)
cur_state.cannibalRight + 2, cur_state.missionaryRight)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
cur_state.cannibalRight + 1, cur_state.missionaryRight + 1)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
cur_state.cannibalRight, cur_state.missionaryRight + 1)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
P a g e | 36
cur_state.cannibalRight + 1, cur_state.missionaryRight)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
else:
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)
cur_state.cannibalRight - 1, cur_state.missionaryRight - 1)
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
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)
P a g e | 38
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)
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)):
P a g e | 39
state = path[len(path) - t - 1]
str(state.missionaryRight) + ")")
def main():
solution = breadth_first_search()
print ("(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)")
print_solution(solution)
if __name__ == "__main__":
main()
P a g e | 40
Output:
P a g e | 41
Solution:
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_):
def string_to_list(string_):
if element == element_to_find:
P a g e | 42
return ir, ic
# we create a cache for the goal position of each piece, so we don't have to
goal_positions = {}
rows_goal = string_to_list(GOAL)
class EigthPuzzleProblem(SearchProblem):
rows = string_to_list(state)
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
'''Return the resulting state after moving a piece to the empty space.
rows = string_to_list(state)
return list_to_string(rows)
return 1
'''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
return distance
result = astar(EigthPuzzleProblem(INITIAL))
print(state)
P a g e | 45
Output:
P a g e | 46
PRACTICAL No.-7
Solution:
#first let's import random procedures since we will be shuffling
import random
#next, let's start building list holders so we can place our cards in there:
cardfaces = []
deck = []
for i in range(2,11):
for j in range(4):
for k in range(4):
for l in range(13):
#this makes each card, cycling through suits, but first through faces
deck.append(card)
random.shuffle(deck)
for m in range(52):
print(deck[m])
Output: