0% found this document useful (0 votes)
30 views58 pages

Artificial Intelligence.r

Uploaded by

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

Artificial Intelligence.r

Uploaded by

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

Name :Rasika Rajesh Dethe

Roll no : 2024032003

Class: TY IT

Subject: Artificial Intelligence

__________________________________________________________________

PRACTICAL NO-1

A. Write a program to implement depth first search algorithm.

B. Write a program to implement breadth first search algorithm

AIM:-

Write a program to implement depth first search algorithm.

GRAPH:-

PYTHON CODE:-

Graph1 = {

‘A’: set([‘B’, ‘C’]),

‘B’: set([‘A’, ‘D’, ‘E’]),

‘C’: set([‘A’, ‘F’]),


TY.IT
2024032003

‘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:-

AIM:-

Write a program to implement breadth first search algorithm.


TY.IT

2024032003

GRAPH:-

PYTHON CODE:-

# sample graph implemented as a dictionary

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’])

#Implement Logic of BFS

Def bfs(start):

Queue = [start]

Levels={} #This Dict Keeps track of levels

Levels[start]=0 #Depth of start node is 0 Visited = set(start)


TY.IT

2024032003
While queue:

Node = queue.pop(0)

Neighbours=graph[node]

For neighbor in neighbours:

If neighbor not in visited:

Queue.append(neighbor)

Visited.add(neighbor)

Levels[neighbor]= levels[node]+1

Print(levels) #print graph level

Return visited

Print(str(bfs(‘A’))) #print graph node

#For Finding Breadth First Search Path

Def bfs_paths(graph, start, goal):

Queue = [(start, [start])]

While queue:
TY.IT
2024032003

(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(result)# [[‘A’, ‘C’, ‘F’], [‘A’, ‘B’, ‘E’, ‘F’]]

#For finding 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’)


TY.IT

2024032003

Print(result1)# [‘A’, ‘C’, ‘F’]

OUTPUT

Practical no-2

A. Write a program to simulate 4-Queen / N-Queen problem.

B. Write a program to solve tower of Hanoi problem.

Aim:-

Write a program to simulate 4-Queen / N-Queen problem

PYTHON CODE:-

Class QueenChessBoard:

Def __init__(self, size):

# board has dimensions size x size

Self.size = size

# columns[r] is a number c if a queen is placed at row r and column c. # columns[r]


is out of range if no queen is place in row r.

# Thus after all queens are placed, they will be at positions

# (columns[0], 0), (columns[1], 1), ... (columns[size – 1], size – 1)


TY.IT

2024032003

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):

# index of next row

Row = len(self.columns)

# check column

For queen_column in self.columns:

If column == queen_column:

Return False

# check diagonal

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


TY.IT
2024032003

If queen_column – queen_row == column – row:

Return False

# check other diagonal

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=’ ‘)
TY.IT

20240232003

Print()

Def solve_queen(size):

“””Display a chessboard for each possible configuration of placing n

Queens on an n x n chessboard and print the number of such

Configurations.”””

Board = QueenChessBoard(size)

Number_of_solutions = 0

Row = 0

Column = 0

# iterate over rows of board

While True:

# place queen in next row While

column < size:

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

# if could not find column to place in or if board is full

If (column == size or row == size):

# if board is full, we have a solution If

row == size:

Board.display()

Print()

Number_of_solutions += 1

# small optimization:

# In a board that already has queens placed in all rows except

# the last, we know there can only be at most one position in


TY.IT

2024032003

# the last row where a queen can be placed. In this case, there

# is a valid position in the last row. Thus we can backtrack two

# times to reach the second last row.

Board.remove_in_current_row()

Row -= 1

# now backtrack

Try:

Prev_column = board.remove_in_current_row()

Except IndexError:

# all queens removed

# thus no more possible configurations

Break

# try previous row again

Row -= 1

# start checking at column = (1 + value of column in previous row)


TY.IT

2024032003

Column = 1 + prev_column

Print(‘Number of solutions:’, number_of_solutions)

N = int(input(‘Enter n: ‘))

Solve_queen(n)

OUTPUT:

AIM:-

Write a program to solve tower of Hanoi problem.

DIAGRAM:

PYTHON 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):
TY.IT

2024032003

print(“moving disk from”,fp,”to”,tp)

moveTower(3,”A”,”B,C”)

PRACTICAL NO.-3

A. Write a program to implement alpha beta search.

B. Write a program for Hill climbing problem.

AIM:-

Write a program to implement alpha beta search.

PYTHON CODE

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
TY.IT 2024032003

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:


TY.IT
2024032003

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

16 | P a g e

Global pruned

Global root

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


TY.IT 2024032003

If __name__ == “__main__”:

Print (“(alpha, beta): “, alpha, beta)

Print (“Result: “, tree)

Print (“Times pruned: “, pruned)

Return (alpha, beta, tree, pruned)

If __name__ == “__main__”:

Alphabeta(None)

OUTPUT

AIM:-

Write a program for Hill climbing problem.

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]

def distance(x1, y1, x2, y2):

dist = math.pow(x2-x1, 2) + math.pow(y2-y1, 2)

return dist

def sumOfDistances(x1, y1, px1, py1, px2, py2, px3, py3, px4, py4):

d1 = distance(x1, y1, px1, py1)

d2 = distance(x1, y1, px2, py2)

d3 = distance(x1, y1, px3, py3)

d4 = distance(x1, y1, px4, py4)

return d1 + d2 + d3 + d4 def newDistance(x1, y1,

point1, point2, point3, point4):


TY.IT

2024032003

d1 = [x1, y1]

d1temp = sumOfDistances(x1, y1, point1[0],point1[1], point2[0],point2[1],

point3[0],point3[1], point4[0],point4[1] )

d1.append(d1temp)

return d1

minDistance = sumOfDistances(startingPoint[0], startingPoint[1],

point1[0],point1[1], point2[0],point2[1],

point3[0],point3[1], point4[0],point4[1] )

flag = True

def newPoints(minimum, d1, d2, d3, d4):

if d1[2] == minimum:

return [d1[0], d1[1]]

elif d2[2] == minimum:

return [d2[0], d2[1]]

elif d3[2] == minimum:


TY.IT 2024032003

return [d3[0], d3[1]]

elif d4[2] == minimum:

return [d4[0], d4[1]]

i=1

while flag:

d1 = newDistance(startingPoint[0]+increment, startingPoint[1], point1, point2,

point3, point4)

d2 = newDistance(startingPoint[0]-increment, startingPoint[1], point1, point2,

point3, point4)

d3 = newDistance(startingPoint[0], startingPoint[1]+increment, point1, point2,

point3, point4)

d4 = newDistance(startingPoint[0], startingPoint[1]-increment, point1, point2,

point3, point4)

print (i,’ ‘, round(startingPoint[0], 2), round(startingPoint[1], 2))


TY.IT

2024032003

minimum = min(d1[2], d2[2], d3[2], d4[2])

if minimum < minDistance:

startingPoint = newPoints(minimum, d1, d2, d3, d4)

minDistance = minimum

#print i,’ ‘, round(startingPoint[0], 2), round(startingPoint[1],2)

i+=1 else:

flag = False

OUTPUT

Practical no-4

A. Write a program to implement A* algorithm.

B. Write a program to implement AO* algorithm.

Aim:-

Write a program to implement A* algorithm.

Note:

Install 2 package in python scripts directory using pip command.


TY.IT
2024032003

1. Pip install simpleai

2. Pip install pydot flask

PYTHON 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


TY.IT 2024032003

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:-

Practical no-5

A. Write a program to solve water jug problem.

B. Design the simulation of tic – tac – toe game using min-max algorithm.

Aim:-
TY.IT
2024032003

Write a program to solve water jug problem.

Diagram:-

Python Code:-

# 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 = []
TY.IT

2024032003

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
TY.IT
2024032003

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:
TY.IT
2024032003

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):
TY.IT

2024032003

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+c<=x):

If( get_all_states((a+c, b, 0)) ):

Ans.append(state)

Return True Else:

If( get_all_states((x, b, c-(x-a))) ):

Ans.append(state)
TY.IT

2024032003
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:
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’

#This Function Draws Game Board 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(“ | | “)

#This Function Checks position is empty or not


TY.IT
2024032003

Def CheckPosition(x):

If(board[x] == ‘ ‘):

Return True

Else:

Return False

#This Function Checks player has won or not

Def CheckWin():

Global Game

#Horizontal winning condition

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
TY.IT 2024032003

Elif(board[7] == board[8] and board[8] == board[9] and board[7] != ‘ ‘):

Game = Win

#Vertical Winning Condition

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

#Diagonal Winning Condition

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

#Match Tie or Draw Condition


TY.IT

2024032003

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 [O]\n”)

Print()

Print()

Print(“Please Wait...”)

Time.sleep(1)

While(Game == Running):

Os.system(‘cls’)

DrawBoard()
TY.IT

2024032003

If(player % 2 != 0):

Print(“Player 1’s chance”)

Mark = ‘X’

Else:

Print(“Player 2’s chance”)

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

To go with “X” and who wants go with “O”.

2. Only one player can play at a time.


TY.IT
2024032003

3. If any of the players have filled a square then the other player and the same

Player cannot override that square.

4. There are only two conditions that may match will be draw or may win.

5. The player that succeeds in placing three respective marks (X or O) in a

Horizontal, vertical or diagonal row wins the game.

OUTPUT

Python Code:-

Import math

# Missionaries and Cannibals Problem

Class State():

Def __init__(self, cannibalLeft, missionaryLeft, boat, cannibalRight,

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):

if self.cannibalLeft == 0 and self.missionaryLeft == 0:

return True

else:

return False

def is_valid(self):

if self.missionaryLeft >= 0 and self.missionaryRight >= 0 \

and self.cannibalLeft >= 0 and self.cannibalRight >= 0 \

and (self.missionaryLeft == 0 or self.missionaryLeft >=

self.cannibalLeft) \
TY.IT

2024032003

and (self.missionaryRight == 0 or self.missionaryRight >=

self.cannibalRight):

return True

else:

return False

def __eq__(self, other):

return self.cannibalLeft == other.cannibalLeft and self.missionaryLeft

== other.missionaryLeft \

And self.boat == other.boat and self.cannibalRight ==

Other.cannibalRight \

And self.missionaryRight == other.missionaryRight

Def __hash__(self):

Return hash((self.cannibalLeft, self.missionaryLeft, self.boat,

Self.cannibalRight, self.missionaryRight))

Def successors(cur_state):
TY.IT
2024032003

Children = [];

If cur_state.boat == ‘left’:

New_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft –

2, ‘right’,

Cur_state.cannibalRight, cur_state.missionaryRight + 2)

## Two missionaries cross left to right.

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)

## Two cannibals cross left to right.

If new_state.is_valid():
TY.IT
2024032003

New_state.parent = cur_state

Children.append(new_state)

New_state = State(cur_state.cannibalLeft – 1, cur_state.missionaryLeft

- 1, ‘right’,

Cur_state.cannibalRight + 1, cur_state.missionaryRight + 1)

## One missionary and one cannibal cross left to right.

If new_state.is_valid():

New_state.parent = cur_state

Children.append(new_state)

Right’,

Cur_state.cannibalRight, cur_state.missionaryRight + 1)

## One missionary crosses left to right.

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)

## One cannibal crosses left to right.

If new_state.is_valid():

New_state.parent = cur_state

Children.append(new_state)

Else:

New_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft +

2, ‘left’,

Cur_state.cannibalRight, cur_state.missionaryRight – 2)

## Two missionaries cross right to left.

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)

## Two cannibals cross right to left.

If new_state.is_valid():

New_state.parent = cur_state

Children.append(new_state)

New_state = State(cur_state.cannibalLeft + 1, cur_state.missionaryLeft

+ 1, ‘left’,

Cur_state.cannibalRight – 1, cur_state.missionaryRight – 1)

## One missionary and one cannibal cross right to left.

If new_state.is_valid():
TY.IT

2024032003

New_state.parent = cur_state

Children.append(new_state)

New_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft +

1, ‘left’,

Cur_state.cannibalRight, cur_state.missionaryRight – 1)

## One missionary crosses right to left.

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)

## One cannibal crosses right to left.

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

For child in children:

If (child not in explored) or (child not in frontier):

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]

Print (“(“ + str(state.cannibalLeft) + “,” +

Str(state.missionaryLeft) \
TY.IT 2024032003

+ “,” + state.boat + “,” + str(state.cannibalRight) + “,” + \

Str(state.missionaryRight) + “)”)

Def main():

Solution = breadth_first_search()

Print (“Missionaries and Cannibals solution:”)

Print (“(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)”)

Print_solution(solution)

# if called from the command line, call main()

If __name__ == “__main__”:

main()

AIM:-

Design an application to simulate number puzzle problem.

PYHTON CODE:-

‘’’

8 puzzle problem, a smaller version of the fifteen puzzle:

States are defined as string representations of the pieces on the puzzle.


TY.IT
2024032003

Actions denote what piece will be moved to the empty space.

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.

For example, the state (string):

‘1-2-3

4-5-6

7-8-e’

Will become (in lists):

[[‘1’, ‘2’, ‘3’],

[‘4’, ‘5’, ‘6’],

[‘7’, ‘8’, ‘e’]]

‘’’

From __future__ import print_function

From simpleai.search import astar, SearchProblem


2024032003
TY.IT

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):


TY.IT
2024032003

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 = []
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

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’)


TY.IT

2024032003

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, i

But needed.

‘’’

Return 1
TY.IT
2024032003

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))

For action, state in result.path():

Print(‘Move number’, action)

Print(state)
2024032003
TY.IT

OUTPUT:

PRACTICAL No.-7

A. Write a program to shuffle Deck of cards.

B. Solve traveling salesman problem using artificial intelligence technique.

Aim:-

Write a program to shuffle Deck of cards.

Diagram:-

Python Code:-

#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 = []

Suits = [“Hearts”, “Diamonds”, “Clubs”, “Spades”]

Royals = [“J”, “Q”, “K”, “A”]

Deck = []
TY.IT
2024032003

#now, let’s start using loops to add our content:

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)

Cardfaces.append(royals[j]) #this will add the royal faces to the cardbase

For k in range(4):

For l in range(13):

Card = (cardfaces[l] + “ of “ + suits[k])

#this makes each card, cycling through suits, but first through faces

Deck.append(card)

#this adds the information to the “full deck” we want to make

#now let’s shuffle our deck!

Random.shuffle(deck)

#now let’s see the cards!

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

Import itertools, random

# make a deck of cards

Deck = list(itertools.product(range(1,14),[‘Spade’,’Heart’,’Diamond’,’Club’]))

# shuffle the cards

Random.shuffle(deck)

# draw five cards

Print(“You got:”)

For i in range(5):

Print(deck[i][0], “of”, deck[i][1])


TY.IT

2024032003

Output:-

PRACTICAL No.-8

A. Solve the block of World problem.

B. Solve constraint satisfaction problem

Aim:-

Implementation Of Constraints Satisfactions Problem

PYTHON CODE:

From __future__ import print_function

From simpleai.search import CspProblem, backtrack, min_conflicts,

MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE,

LEAST_CONSTRAINING_VALUE

Variables = (‘WA’, ‘NT’, ‘SA’, ‘Q’, ‘NSW’, ‘V’, ‘T’)

Domains = dict((v, [‘red’, ‘green’, ‘blue’]) for v in variables)

Def const_different(variables, values):


TY.IT
2024032003

Return values[0] != values[1] # expect the value of the neighbors to be different

Constraints = [

((‘WA’, ‘NT’), const_different),

((‘WA’, ‘SA’), const_different),

((‘SA’, ‘NT’), const_different),

((‘SA’, ‘Q’), const_different),

((‘NT’, ‘Q’), const_different),

((‘SA’, ‘NSW’), const_different),

((‘Q’, ‘NSW’), const_different),

((‘SA’, ‘V’), const_different),

((‘NSW’, ‘V’), const_different),

My_problem = CspProblem(variables, domains, 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:

You might also like