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

Python Programs for AI Algorithms

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 DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views58 pages

Python Programs for AI Algorithms

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 DOCX, PDF, TXT or read online on Scribd

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


[Link]
2024032003

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

‘E’: set([‘B’, ‘F’]),

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

Def dfs(graph, node, visited):

If node not in visited:

[Link](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.


[Link]

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)


[Link]

2024032003
While queue:

Node = [Link](0)

Neighbours=graph[node]

For neighbor in

neighbours: If neighbor

not in visited:

[Link](neighbor)

[Link](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:
[Link]
2024032003

(vertex, path) = [Link](0)

For next in graph[vertex] – set(path):

If next == goal:

Yield path + [next]

Else:

[Link]((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’)


[Link]

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

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


[Link]

2024032003

[Link] = []

Def place_in_next_row(self, column):

[Link](column)

Def remove_in_current_row(self):

Return [Link]()

Def is_this_column_safe_in_next_row(self, column):

# index of next row

Row = len([Link])

# check column

For queen_column in [Link]:

If column == queen_column:

Return False

# check diagonal

For queen_row, queen_column in enumerate([Link]):


[Link]
2024032003

If queen_column – queen_row == column – row:

Return False

# check other diagonal

For queen_row, queen_column in enumerate([Link]):

If (([Link] – queen_column) – queen_row

== ([Link] – column) – row):

Return False

Return True

Def display(self):

For row in range([Link]):

For column in

range([Link]): If column

== [Link][row]:

Print(‘Q’, end=’ ‘)

Else:

Print(‘.’, end=’ ‘)
[Link]

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)
[Link]

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:

[Link]()

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


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)


[Link]

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):
[Link]

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
[Link] 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:


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 |

Page

Global pruned

Global root

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


[Link] 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(Non

e) OUTPUT

AIM:-

Write a program for Hill climbing problem.

DIAGRAM:-

PYTHON CODE:

Import math

Increment = 0.1

startingPoint = [1, 1]
[Link]
2024032003

point1 = [1,5]

point2 = [6,4]

point3 = [5,2]

point4 = [2,1]

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

dist = [Link](x2-x1, 2) + [Link](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):
2024032003

d1 = [x1, y1]

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

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

[Link](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:


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


[Link]

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.


[Link]
2024032003

1. Pip install simpleai

2. Pip install pydot flask

PYTHON CODE:-

From [Link] 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


[Link] 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([Link])

Print([Link]())

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

[Link](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
[Link]
2024032003

If(a+b<=y):

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

[Link](state)

Return

True Else:

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

[Link](state)

Return True

#empty a into c

If(a+c<=z):

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

[Link](state)

Return True

Else:
2024032003

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

[Link](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)) ):

[Link](state)

Return True

Else:

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

[Link](state)

Return True

#empty b into c

If(b+c<=z):
[Link]

2024032003

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

[Link](sta

te) Return True

Else:

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

[Link](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)) ):

[Link](state)

Return True Else:

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

): [Link](state)
[Link]

2024032003
Return True

#empty c into b

If(b+c<=y):

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

[Link](state)

Return True

Else:

If( get_all_states((a, y, c-(y-

b))) ): [Link](state)

Return

True

Return

False

Initial_state = (12,0,0)

Print(“Starting work...\n”)

Get_all_states(initial_state)

[Link]()

For i in ans:
[Link] 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
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


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


[Link]

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

[Link](1)

While(Game == Running):

[Link](‘cls’)

DrawBoard()
[Link]

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

[Link](‘cls’)
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.


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

[Link] = cannibalLeft

[Link] = missionaryLeft
2024032003

[Link] = boat

[Link] = cannibalRight

[Link] = missionaryRight

[Link] = None

def is_goal(self):

if [Link] == 0 and [Link] == 0:

return True

else:

return False

def is_valid(self):

if [Link] >= 0 and [Link] >= 0 \

and [Link] >= 0 and [Link] >= 0 \

and ([Link] == 0 or [Link] >=

[Link]) \
[Link]

2024032003

and ([Link] == 0 or [Link] >=

[Link]):

return True

else:

return False

def eq (self, other):

return [Link] == [Link] and [Link]

== [Link] \

And [Link] == [Link] and [Link] ==

[Link] \

And [Link] == [Link]

Def hash (self):

Return hash(([Link], [Link], [Link],

[Link], [Link]))

Def successors(cur_state):
[Link]
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

[Link](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():
[Link]
2024032003

New_state.parent = cur_state

[Link](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

[Link](new_sta

te) Right’,

Cur_state.cannibalRight, cur_state.missionaryRight + 1)

## One missionary crosses left to right.

If new_state.is_valid():

New_state.parent = cur_state
[Link]

2024032003

[Link](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

[Link](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():
2024032003

New_state.parent = cur_state

[Link](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

[Link](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():
[Link]

2024032003

New_state.parent = cur_state

[Link](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

[Link](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

[Link](new_state)
[Link]

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

[Link](initial_stat

e) While frontier:

State = [Link](0)

If state.is_goal():

Return state

[Link](state)

Children = successors(state)
[Link] 2024032003

For child in children:

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

[Link](child)

Return None

Def print_solution(solution):

Path = []

[Link](solution)

Parent = [Link]

While parent:

[Link](parent)

Parent = [Link]

For t in range(len(path)):

State = path[len(path) – t – 1]

Print (“(“ + str([Link]) + “,” +

Str([Link]) \
[Link] 2024032003

+ “,” + [Link] + “,” + str([Link]) + “,” + \

Str([Link]) + “)”)

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.


[Link]
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 [Link] import astar, SearchProblem


2024032003
[Link]

From [Link] 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 [[Link](‘-‘) 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):


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

2024032003

If row_e > 0:

[Link](rows[row_e – 1][col_e])

If row_e < 2:

[Link](rows[row_e + 1][col_e])

If col_e > 0:

[Link](rows[row_e][col_e – 1])

If col_e < 2:

[Link](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’)


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
[Link]
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 [Link]():

Print(‘Move number’,

action) Print(state)
2024032003

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

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

For i in range(2,11):

[Link](str(i)) #this adds numbers 2-10 and converts them to

string data For j in range(4)

[Link](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

[Link](card)

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

#now let’s shuffle our deck!

[Link](deck)

#now let’s see the cards!

For m in range(52):
[Link]
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([Link](range(1,14),[‘Spade’,’Heart’,’Diamond’,’Club’]))

# shuffle the cards

[Link](deck)

# draw five cards

Print(“You got:”)

For i in range(5):

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


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 [Link] 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):


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

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:

Common questions

Powered by AI

Alpha-Beta pruning optimizes tree searching by eliminating branches that cannot possibly influence the final decision, thus reducing the number of nodes evaluated in the search tree. It uses two values, alpha and beta, to represent the maximum lower bound and minimum upper bound of possible scores, respectively. As the algorithm traverses the tree, if it finds a scenario where a better move can be assured (i.e., a branch value doesn't improve or is worse than the assured best), that branch is cut (pruned). The primary advantages are increased efficiency in time and reduced complexity, allowing the algorithm to evaluate larger search trees effectively without redundant checks .

Backtracking in the N-Queens problem is used to explore configurations where queens are placed on a chessboard such that no two queens attack each other. The algorithm places a queen in a row and proceeds to the next row, checking safe columns using the method "is_this_column_safe_in_next_row" which verifies column and diagonal threats. If a safe position is not found, it backtracks by removing the last placed queen (using "remove_in_current_row") and attempts the next position. This continues until all valid configurations are found, utilizing recursion to manage the state of the board .

The core difference between DFS and BFS lies in their approach to exploring the graph. DFS uses a stack-based approach (implicitly via recursion) to explore as far as possible along each branch before backtracking, which is evident in the use of recursion to visit nodes in the provided implementation . In contrast, BFS uses a queue to explore all neighbors of a node before moving to the next level, which is reflected in the code structure where a queue manages the nodes to be visited, ensuring that all nodes at the current depth are processed before proceeding deeper .

In the provided example, the Hill Climbing algorithm incrementally adjusts position coordinates to minimize the sum of distances to fixed points until a local minimum is found. While effective at finding a local minimum quickly by evaluating neighbor positions for better outcomes, it inherently risks stalling at local optima, lacking the capacity to escape without further augmentation (e.g., random restarts or simulated annealing). The algorithm's deterministic nature limits global optimization efficiency, as it doesn't explore less promising but potentially superior alternatives, demonstrating limitations in search space exploration .

The A* search algorithm employs heuristic information to guide the search process towards the most promising nodes, enhancing efficiency by prioritizing paths based on a cost function. This heuristic, often denoted as h(n), estimates the cost to reach the goal from node n. It combines with the actual cost from the start node to n, represented as g(n), creating a total estimated cost function, f(n) = g(n) + h(n). This helps prioritize nodes that seem promising based on potential and actual costs, allowing A* to focus on the path that appears to minimize the total cost to the goal. In the provided implementation, the heuristic function calculates misalignments between current and goal states, strategically guiding the search .

The Water Jug problem is solved using a depth-first search approach where the algorithm explores possible states by transferring water between jugs. The algorithm recursively attempts different jug transfers while maintaining state awareness through a "memory" dictionary to avoid revisits of the same state. Each state represents a configuration of the water levels in the jugs. The DFS explores these configurations by recursively attempting all possible valid transfers, continuously checking if a state achieves the goal configuration (e.g., achieving water levels [6,6,0]). This way, the search explores potential solutions depth-wise before backtracking .

The implemented Tic-Tac-Toe game observes win and draw conditions based on traditional rules. A win occurs when a player places three of their marks (either 'X' or 'O') consecutively in a row, column, or diagonal. The game checks these conditions after each move by evaluating board state, using functions to verify whether these alignments occur . A draw condition (game tie) is declared when all board positions are filled without any win condition met, resulting in no further moves possible . These game rules ensure a clear endpoint for each session.

The solution to the Missionaries and Cannibals problem employs a state validation check within the "is_valid" method to ensure that missionaries are never outnumbered by cannibals on either riverbank, which could lead to the missionaries being eaten. This function checks the current number of missionaries and cannibals on both sides, ensuring that the missionaries are either equal to or more than the number of cannibals, or their count is zero (indicating no risk). This validation is applied after every potential move to guarantee that any transitioning state remains safe, thus preventing any illegal state transitions .

The Tower of Hanoi problem is solved using a recursive Python function named "moveTower". The algorithm involves moving a tower of disks from one pole to another by using an auxiliary pole, adhering to the rule that a larger disk cannot be placed on a smaller disk. The function calls itself to move smaller sub-towers between poles, with the base case being a tower height no larger than one, at which point the disk is moved directly. The strategy involves moving the smaller tower to the auxiliary pole, moving the largest disk to the destination, and finally, moving the sub-tower atop the largest disk .

The Tic-Tac-Toe game employs the Minimax algorithm to simulate optimal moves by predicting all possible game outcomes and minimizing the possible loss for the worst-case scenario. The algorithm recursively calculates the value of each move by simulating the game from that point onwards, assessing the potential win/loss outcomes. It assumes optimal play by both participants, making it possible to determine the best possible move at any given time by choosing the path with the highest evaluation score (or lowest score in the opponent's turn). This ensures that the game is played with the best strategy, minimizing the chances of losing while maximizing victory opportunities .

You might also like