Artificial Intelligence.r
Artificial Intelligence.r
Roll no : 2024032003
Class: TY IT
__________________________________________________________________
PRACTICAL NO-1
AIM:-
GRAPH:-
PYTHON CODE:-
Graph1 = {
‘D’: set([‘B’]),
Visited.append(node)
For n in graph[node]:
visited
Print(visited)
OUTPUT:-
AIM:-
2024032003
GRAPH:-
PYTHON CODE:-
‘D’: set([‘B’]),
Def bfs(start):
Queue = [start]
2024032003
While queue:
Node = queue.pop(0)
Neighbours=graph[node]
Queue.append(neighbor)
Visited.add(neighbor)
Levels[neighbor]= levels[node]+1
Return visited
While queue:
TY.IT
2024032003
If next == goal:
Else:
Try:
Except StopIteration:
Return None
2024032003
OUTPUT
Practical no-2
Aim:-
PYTHON CODE:-
Class QueenChessBoard:
Self.size = size
2024032003
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]:
Print(‘Q’, end=’ ‘)
Else:
Print(‘.’, end=’ ‘)
TY.IT
20240232003
Print()
Def solve_queen(size):
Configurations.”””
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)
TY.IT
2024032003
Row += 1
Column = 0
Break
Else:
Column += 1
row == size:
Board.display()
Print()
Number_of_solutions += 1
# small optimization:
2024032003
# the last row where a queen can be placed. In this case, there
Board.remove_in_current_row()
Row -= 1
# now backtrack
Try:
Prev_column = board.remove_in_current_row()
Except IndexError:
Break
Row -= 1
2024032003
Column = 1 + prev_column
N = int(input(‘Enter n: ‘))
Solve_queen(n)
OUTPUT:
AIM:-
DIAGRAM:
PYTHON CODE:
If height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
TY.IT
2024032003
moveTower(3,”A”,”B,C”)
PRACTICAL NO.-3
AIM:-
PYTHON CODE
Tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
Root = 0
Pruned = 0
Global tree
Global root
Global pruned
TY.IT 2024032003
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
16 | P a g e
Global pruned
Global root
If __name__ == “__main__”:
If __name__ == “__main__”:
Alphabeta(None)
OUTPUT
AIM:-
DIAGRAM:-
PYTHON CODE:
Import math
Increment = 0.1
startingPoint = [1, 1]
TY.IT
2024032003
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):
2024032003
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:
point3, point4)
point3, point4)
point3, point4)
point3, point4)
2024032003
minDistance = minimum
i+=1 else:
flag = False
OUTPUT
Practical no-4
Aim:-
Note:
PYTHON CODE:-
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:-
Practical no-5
B. Design the simulation of tic – tac – toe game using min-max algorithm.
Aim:-
TY.IT
2024032003
Diagram:-
Python Code:-
Capacity = (12,8,5)
X = capacity[0]
Y = capacity[1]
Z = capacity[2]
Memory = {}
Ans = []
TY.IT
2024032003
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
TY.IT
2024032003
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:
TY.IT
2024032003
Ans.append(state)
Return True
#empty jug b
If(b>0):
Ans.append(state)
Return True
Else:
Ans.append(state)
Return True
#empty b into c
If(b+c<=z):
TY.IT
2024032003
Ans.append(state)
Ans.append(state)
Return True
#empty jug c
If(c>0):
#empty c into a
If(a+c<=x):
Ans.append(state)
Ans.append(state)
TY.IT
2024032003
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”)
Get_all_states(initial_state)
Ans.reverse()
For i in ans:
TY.IT 2024032003
Print(i)
Output:-
Aim:-
Design the simulation of TIC – TAC –TOE game using min-max algorithm
Diagram:-
Python Code:
Import os
Import time
Board = [‘ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘,’ ‘]
Player = 1
########win Flags##########
Win = 1
Draw = -1
TY.IT
2024032003
Running = 0
Stop = 1
###########################
Game = Running
Mark = ‘X’
DrawBoard():
Print(“ %c | %c | %c “ % (board[1],board[2],board[3]))
Print(“___|___|___”)
Print(“ %c | %c | %c “ % (board[4],board[5],board[6]))
Print(“___|___|___”)
Def CheckPosition(x):
If(board[x] == ‘ ‘):
Return True
Else:
Return False
Def CheckWin():
Global Game
Game = Win
Game = Win
TY.IT 2024032003
Game = Win
Game = Win
Game = Win
Game=Win
Game = Win
Game=Win
2024032003
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()
TY.IT
2024032003
If(player % 2 != 0):
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’)
TY.IT
2024032003
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”)
NOTE:-
Game Rules
1. Traditionally the first player plays with “X”. So you can decide who wants
3. If any of the players have filled a square then the other player and the same
4. There are only two conditions that may match will be draw or may win.
OUTPUT
Python Code:-
Import math
Class State():
missionaryRight):
self.cannibalLeft = cannibalLeft
self.missionaryLeft = missionaryLeft
TY.IT
2024032003
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) \
TY.IT
2024032003
self.cannibalRight):
return True
else:
return False
== other.missionaryLeft \
Other.cannibalRight \
Def __hash__(self):
Self.cannibalRight, self.missionaryRight))
Def successors(cur_state):
TY.IT
2024032003
Children = [];
If cur_state.boat == ‘left’:
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():
TY.IT
2024032003
New_state.parent = cur_state
Children.append(new_state)
- 1, ‘right’,
Cur_state.cannibalRight + 1, cur_state.missionaryRight + 1)
If new_state.is_valid():
New_state.parent = cur_state
Children.append(new_state)
Right’,
Cur_state.cannibalRight, cur_state.missionaryRight + 1)
If new_state.is_valid():
New_state.parent = cur_state
TY.IT
2024032003
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
Children.append(new_state)
Else:
2, ‘left’,
Cur_state.cannibalRight, cur_state.missionaryRight – 2)
If new_state.is_valid():
TY.IT
2024032003
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)
+ 1, ‘left’,
Cur_state.cannibalRight – 1, cur_state.missionaryRight – 1)
If new_state.is_valid():
TY.IT
2024032003
New_state.parent = cur_state
Children.append(new_state)
1, ‘left’,
Cur_state.cannibalRight, cur_state.missionaryRight – 1)
If new_state.is_valid():
New_state.parent = cur_state
Children.append(new_state)
Cur_state.cannibalRight – 1, cur_state.missionaryRight)
If new_state.is_valid():
New_state.parent = cur_state
Children.append(new_state)
TY.IT
2024032003
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)
TY.IT 2024032003
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.missionaryLeft) \
TY.IT 2024032003
Str(state.missionaryRight) + “)”)
Def main():
Solution = breadth_first_search()
Print (“(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)”)
Print_solution(solution)
If __name__ == “__main__”:
main()
AIM:-
PYHTON CODE:-
‘’’
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.
‘1-2-3
4-5-6
7-8-e’
‘’’
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_):
find_location(rows, element_to_find):
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
Goal_positions = {}
Rows_goal = string_to_list(GOAL)
Class EigthPuzzleProblem(SearchProblem):
Rows = string_to_list(state)
Actions = []
TY.IT
2024032003
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)
2024032003
Rows[row_e][col_e]
Return list_to_string(rows)
But needed.
‘’’
Return 1
TY.IT
2024032003
‘’’
Rows = string_to_list(state)
Distance = 0
Return distance
Result = astar(EigthPuzzleProblem(INITIAL))
Print(state)
2024032003
TY.IT
OUTPUT:
PRACTICAL No.-7
Aim:-
Diagram:-
Python Code:-
Import random
#next, let’s start building list holders so we can place our cards in there:
Cardfaces = []
Deck = []
TY.IT
2024032003
For i in range(2,11):
Cardfaces.append(str(i)) #this adds numbers 2-10 and converts them to string data
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):
TY.IT
2024032003
Print(deck[m])
OR
# Python program to shuffle a deck of card using the module random and
Draw 5 cards
# import modules
Deck = list(itertools.product(range(1,14),[‘Spade’,’Heart’,’Diamond’,’Club’]))
Random.shuffle(deck)
Print(“You got:”)
For i in range(5):
2024032003
Output:-
PRACTICAL No.-8
Aim:-
PYTHON CODE:
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE,
LEAST_CONSTRAINING_VALUE
Constraints = [
Print(backtrack(my_problem))
2024032003
TY.IT
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))
Print(backtrack(my_problem,
Variable_heuristic=HIGHEST_DEGREE_VARIABLE,
Value_heuristic=LEAST_CONSTRAINING_VALUE))
Print(min_conflicts(my_problem))
OUTPUT: