Artificial Intelligencefile
Artificial Intelligencefile
Artificial Intelligencefile
1 Date: 08/08/2019
Practical Name: (a) Write a program to implement depth first search
algorithm.
Code:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph=defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DFSUtil(self,v,visited):
visited[v]=True
print(v)
for i in self.graph[v]:
if visited[i]==False:
self.DFSUtil(i,visited)
def DFS(self,v):
visited=[False]*(len(self.graph))
self.DFSUtil(v,visited)
g=Graph()
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,2)
g.addEdge(2,0)
g.addEdge(2,3)
g.addEdge(3,3)
g.DFS(1)
1|Page
Output:
2|Page
Practical No. 1 Date: 08/08/2019
Practical Name: (b) Write a program to implement breadth first search
algorithm.
Code:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph=defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self,s):
visited=[False]*(len(self.graph))
queue=[]
queue.append(s)
visited[s]=True
while queue:
s=queue.pop(0)
print(s,end="")
for i in self.graph[s]:
if visited[i]==False:
queue.append(i)
visited[i]=True
g=Graph()
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,2)
g.addEdge(2,0)
g.addEdge(2,3)
g.addEdge(3,3)
g.BFS(2)
3|Page
Output:
4|Page
Practical No. 2 Date: 14/08/2019
Practical Name: (a) Write a program to simulate 4-Queen / N-Queen
problem.
Code:
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)
if column == queen_column:
return False
return False
return False
return True
def display(self):
if column == self.columns[row]:
else:
5|Page
print('.', end=' ')
print()
def solve_queen(size):
board = QueenChessBoard(size)
number_of_solutions = 0
row = 0
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
board.remove_in_current_row()
row -= 1
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)
6|Page
7|Page
Output:
8|Page
Practical No. 2 Date: 14/08/2019
Practical Name: (b) 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):
moveTower(2,"A","B","C")
Output:
9|Page
Practical No. 3 Date: 21/08/2019
Practical Name: (a) 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
global tree
global root
global pruned
i = 0
if type(child) is list:
if depth % 2 == 1:
else:
i += 1
else:
alpha = child
beta = child
pruned += 1
break
if depth == root:
global tree
10 | P a g e
global pruned
global root
if __name__ == "__main__":
if __name__ == "__main__":
alphabeta(None)
11 | P a g e
Output:
12 | P a g e
Practical No. 3 Date: 21/08/2019
Practical Name: (b) 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 dist
def sumOfDistances(x1, y1, px1, py1, px2, py2, px3, py3, px4, py4):
return d1 + d2 + d3 + d4
d1 = [x1, y1]
d1.append(d1temp)
return d1
13 | P a g e
flag = True
if d1[2] == minimum:
i = 1
while flag:
minDistance = minimum
i+=1
else:
flag = False
14 | P a g e
15 | P a g e
Output:
16 | P a g e
Practical No. 4 Date: 28/08/2019
Practical Name: Write a program to implement A* algorithm.
Code:
from simpleai.search import SearchProblem, astar
class HelloProblem(SearchProblem):
else:
return []
for i in range(len(state))])
problem = HelloProblem(initial_state='')
result = astar(problem)
print(result.state)
print(result.path())
17 | P a g e
Output:
18 | P a g e
Practical No. 5 Date: 28/08/2019
Practical Name: (a) Write a program to solve water jug problem.
Code:
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
if(a>0):
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):
ans.append(state)
return True
else:
ans.append(state)
return True
if(a+c<=z):
if( get_all_states((0,b,a+c)) ):
ans.append(state)
return True
else:
19 | P a g e
if( get_all_states((a-(z-c), b, z)) ):
ans.append(state)
return True
if(b>0):
if(a+b<=x):
ans.append(state)
return True
else:
ans.append(state)
return True
if(b+c<=z):
ans.append(state)
return True
else:
ans.append(state)
return True
if(c>0):
if(a+c<=x):
ans.append(state)
return True
else:
ans.append(state)
return True
if(b+c<=y):
ans.append(state)
return True
else:
20 | P a g e
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)
21 | P a g e
Output:
22 | P a g e
Practical No. 5 Date: 11/09/2019
Practical Name: (b) Design the simulation of tic – tac – toe game using min-
max algorithm.
Code:
import os
import time
board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ']
player = 1
Win = 1
Draw = -1
Running = 0
Stop = 1
Game = Running
Mark = 'X'
def DrawBoard():
print("___|___|___")
print("___|___|___")
print(" | | ")
def CheckPosition(x):
return True
else:
return False
def CheckWin():
global Game
Game = Win
Game = Win
23 | P a g e
elif(board[7] == board[8] and board[8] == board[9] and board[7] != ' '):
Game = Win
Game = Win
Game = Win
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):
Mark = 'X'
24 | P a g e
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")
25 | P a g e
26 | P a g e
Output:
27 | P a g e
Practical No. 6 Date: 18/09/2019
Practical Name: (a) Write a program to solve Missionaries and Cannibals
problem.
Code:
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):
self.cannibalLeft) \
return True
else:
return False
28 | P a g e
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():
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)
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, 'right',
cur_state.cannibalRight + 1,
cur_state.missionaryRight)
29 | P a g e
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
30 | P a g e
children.append(new_state)
return children
def breadth_first_search():
initial_state = State(3,3,'left',0,0)
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)):
state = path[len(path) - t - 1]
str(state.missionaryRight) + ")")
def main():
solution = breadth_first_search()
31 | P a g e
print ("Missionaries and Cannibals solution:")
print ("(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)")
print_solution(solution)
if __name__ == "__main__":
main()
32 | P a g e
33 | P a g e
Output:
34 | P a g e
35 | P a g e
Practical No. 6 Date: 25/09/2019
Practical Name: (b) Design an application to simulate number puzzle
problem.
Code:
from __future__ import print_function
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:
return ir, ic
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])
36 | P a g 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
rows = string_to_list(state)
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 cost(self,state1,action,state2):
return 1
rows = string_to_list(state)
distance = 0
return distance
result = astar(EigthPuzzleProblem(INITIAL))
print(state)
37 | P a g e
38 | P a g e
Output:
39 | P a g e
Practical No. 7 Date: 01/10/2019
Practical Name: (a) Design an application to simulate number puzzle
problem.
Code:
import itertools, random
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))
random.shuffle(deck)
print("You got:")
for i in range(5):
Output:
40 | P a g e
Practical No. 8 Date: 01/10/2019
Practical Name: (a) Design an application to simulate number puzzle
problem.
Code:
from __future__ import print_function
constraints = [
print(backtrack(my_problem))
print(backtrack(my_problem,
variable_heuristic=MOST_CONSTRAINED_VARIABLE))
print(backtrack(my_problem,
variable_heuristic=HIGHEST_DEGREE_VARIABLE))
print(backtrack(my_problem,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(backtrack(my_problem,
variable_heuristic=MOST_CONSTRAINED_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
41 | P a g e
print(backtrack(my_problem,
variable_heuristic=HIGHEST_DEGREE_VARIABLE,
value_heuristic=LEAST_CONSTRAINING_VALUE))
print(min_conflicts(my_problem))
Output:
42 | P a g e