0% found this document useful (0 votes)
118 views33 pages

AI Journal

The document provides code to implement various search and optimization algorithms: 1. Depth-first search and breadth-first search algorithms are implemented on a sample graph to traverse and print nodes. 2. The N-Queen problem is solved using backtracking to place N queens on a chessboard without attacking each other. 3. Alpha-beta pruning is applied to a sample tree to return the optimal value while pruning suboptimal branches. Hill climbing is used to find the optimal position minimizing distances to fixed points. 4. A* search algorithm finds the shortest path to a goal state using heuristics. 5. Water jug problem is solved by simulating pouring actions between jugs of different capacities

Uploaded by

laxman guptta
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)
118 views33 pages

AI Journal

The document provides code to implement various search and optimization algorithms: 1. Depth-first search and breadth-first search algorithms are implemented on a sample graph to traverse and print nodes. 2. The N-Queen problem is solved using backtracking to place N queens on a chessboard without attacking each other. 3. Alpha-beta pruning is applied to a sample tree to return the optimal value while pruning suboptimal branches. Hill climbing is used to find the optimal position minimizing distances to fixed points. 4. A* search algorithm finds the shortest path to a goal state using heuristics. 5. Water jug problem is solved by simulating pouring actions between jugs of different capacities

Uploaded by

laxman guptta
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
You are on page 1/ 33

Practical No : 1

A) Write a program to implement depth first search algorithm

AIM:- Write a program to implement depth first search algorithm.


GRAPH:-

PYTHON CODE:-
# Using a Python dictionary to act as an adjacency list
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
OUTPUT:-

B) Write a program to implement breadth first search algorithm

AIM:- Write a program to implement breadth first search algorithm


GRAPH:-

PYTHON CODE:-
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
OUTPUT:-

Practical No : 2
A) Write a program to simulate 4-Queen / N-Queen problem

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


GRAPH:-
PYTHON CODE:-
# Python3 program to solve N Queen
# Problem using backtracking
global N
N=4

def printSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end = " ")
print()

# A utility function to check if a queen can


# be placed on board[row][col]. Note that this
# function is called when "col" queens are
# already placed in columns from 0 to col -1.
# So we need to check only left side for
# attacking queens
def isSafe(board, row, col):

# Check this row on left side


for i in range(col):
if board[row][i] == 1:
return False

# Check upper diagonal on left side


for i, j in zip(range(row, -1, -1),
range(col, -1, -1)):
if board[i][j] == 1:
return False

# Check lower diagonal on left side


for i, j in zip(range(row, N, 1),
range(col, -1, -1)):
if board[i][j] == 1:
return False

return True

def solveNQUtil(board, col):

# base case: If all queens are placed


# then return true
if col >= N:
return True

# Consider this column and try placing


# this queen in all rows one by one
for i in range(N):

if isSafe(board, i, col):

# Place this queen in board[i][col]


board[i][col] = 1
# recur to place rest of the queens
if solveNQUtil(board, col + 1) == True:
return True

# If placing queen in board[i][col


# doesn't lead to a solution, then
# queen from board[i][col]
board[i][col] = 0

# if the queen can not be placed in any row in


# this column col then return false
return False

# This function solves the N Queen problem using


# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0] ]

if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False

printSolution(board)
return True

# Driver Code
solveNQ()
OUTPUT:-
NOTE:
1. The user is prompted to enter n where n is the number of queens to place and
the size of the board.
2. Solve queens is called on n to display all possible board configurations and the
number of solutions.
B) Write a program to solve tower of Hanoi problem

AIM:- Write a program to solve tower of Hanoi problem.


GRAPH:-

PYTHON CODE:-
def moveTower(height, fp,tp,wp):
if height >=1:
moveTower(height-1,fp,wp,tp)
print("Moving disk from ", fp, " to ",tp)
moveTower(height-1,wp,tp,fp)

moveTower(3,"A","B","C")
OUTPUT:-
Practical No : 3

A) Write a program to implement alpha beta search

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
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:
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
global pruned
global root

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


if __name__ == "__main__":
print ("(alpha, beta): ", alpha, beta)
print ("Result: ", tree)
print ("Times pruned: ", pruned)
return (alpha, beta, tree, pruned)

alphabeta(None)
OUTPUT:-
B) Write a program for Hill climbing problem

AIM:- Write a program for Hill climbing problem.


PYTHON CODE:-
import math

increment = 0.1
startingPoint = [1, 1]
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):


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

AIM:- Write a program to implement A* algorithm

PYTHON CODE:-
#Install the below given libraries via pip
#pip install simpleai
#pip install pydot flask
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

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

AIM:- Program to solve water jug problem

PYTHON CODE:-
def pour(jug1, jug2):
max1, max2, fill = 5, 7, 4 #Change maximum capacity and final capacity
print(jug1, "\t",jug2)
if jug2 is fill:
return
elif jug2 is max2:
pour(0, jug1)
elif jug1 != 0 and jug2 == 0:
pour(0, jug1)
elif jug1 is fill:
pour(jug1, 0)
elif jug1 < max1:
pour(max1, jug2)
elif jug1 < (max2-jug2):
pour(0, (jug1+jug2))
else:
pour(jug1-(max2-jug2), (max2-jug2)+jug2)

print("JUG1\tJUG2")
pour(0, 0)
OUTPUT:-

B) Design the simulation of tic – tac – toe game using min-max algorithm
AIM:- Design the simulation of tic – tac – toe game using min-max algorithm

PYTHON CODE:-
from math import inf as infinity
from random import choice
import platform
import time
from os import system

HUMAN = -1
COMP = +1
board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]

def evaluate(state):
"""
:param state: the state of the current board
:return: +1 if the computer wins; -1 if the human wins; 0 draw
"""
if wins(state, COMP):
score = +1
elif wins(state, HUMAN):
score = -1
else:
score = 0

return score

def wins(state, player):


"""
This function tests if a specific player wins. Possibilities:
* Three rows [X X X] or [O O O]
* Three cols [X X X] or [O O O]
* Two diagonals [X X X] or [O O O]
:param state: the state of the current board
:param player: a human or a computer
:return: True if the player wins
"""
win_state = [
[state[0][0], state[0][1], state[0][2]],
[state[1][0], state[1][1], state[1][2]],
[state[2][0], state[2][1], state[2][2]],
[state[0][0], state[1][0], state[2][0]],
[state[0][1], state[1][1], state[2][1]],
[state[0][2], state[1][2], state[2][2]],
[state[0][0], state[1][1], state[2][2]],
[state[2][0], state[1][1], state[0][2]],
]
if [player, player, player] in win_state:
return True
else:
return False

def game_over(state):
"""
This function test if the human or computer wins
:param state: the state of the current board
:return: True if the human or computer wins
"""
return wins(state, HUMAN) or wins(state, COMP)

def empty_cells(state):
"""
Each empty cell will be added into cells' list
:param state: the state of the current board
:return: a list of empty cells
"""
cells = []
for x, row in enumerate(state):
for y, cell in enumerate(row):
if cell == 0:
cells.append([x, y])

return cells

def valid_move(x, y):


"""
A move is valid if the chosen cell is empty
:param x: X coordinate
:param y: Y coordinate
:return: True if the board[x][y] is empty
"""
if [x, y] in empty_cells(board):
return True
else:
return False

def set_move(x, y, player):


"""
Set the move on board, if the coordinates are valid
:param x: X coordinate
:param y: Y coordinate
:param player: the current player
"""
if valid_move(x, y):
board[x][y] = player
return True
else:
return False

def minimax(state, depth, player):


"""
AI function that choice the best move
:param state: current state of the board
:param depth: node index in the tree (0 <= depth <= 9),
but never nine in this case (see iaturn() function)
:param player: an human or a computer
:return: a list with [the best row, best col, best score]
"""
if player == COMP:
best = [-1, -1, -infinity]
else:
best = [-1, -1, +infinity]

if depth == 0 or game_over(state):
score = evaluate(state)
return [-1, -1, score]

for cell in empty_cells(state):


x, y = cell[0], cell[1]
state[x][y] = player
score = minimax(state, depth - 1, -player)
state[x][y] = 0
score[0], score[1] = x, y

if player == COMP:
if score[2] > best[2]:
best = score # max value
else:
if score[2] < best[2]:
best = score # min value

return best

def clean():
"""
Clears the console
"""
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')

def render(state, c_choice, h_choice):


"""
Print the board on console
:param state: current state of the board
"""

chars = {
-1: h_choice,
+1: c_choice,
0: ' '
}
str_line = '---------------'

print('\n' + str_line)
for row in state:
for cell in row:
symbol = chars[cell]
print(f'| {symbol} |', end='')
print('\n' + str_line)

def ai_turn(c_choice, h_choice):


"""
It calls the minimax function if the depth < 9,
else it choices a random coordinate.
:param c_choice: computer's choice X or O
:param h_choice: human's choice X or O
:return:
"""
depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return

clean()
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)

if depth == 9:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
else:
move = minimax(board, depth, COMP)
x, y = move[0], move[1]

set_move(x, y, COMP)
time.sleep(1)

def human_turn(c_choice, h_choice):


"""
The Human plays choosing a valid move.
:param c_choice: computer's choice X or O
:param h_choice: human's choice X or O
:return:
"""
depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return

# Dictionary of valid moves


move = -1
moves = {
1: [0, 0], 2: [0, 1], 3: [0, 2],
4: [1, 0], 5: [1, 1], 6: [1, 2],
7: [2, 0], 8: [2, 1], 9: [2, 2],
}

clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)

while move < 1 or move > 9:


try:
move = int(input('Use numpad (1..9): '))
coord = moves[move]
can_move = set_move(coord[0], coord[1], HUMAN)

if not can_move:
print('Bad move')
move = -1
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')

def start_game():
"""
Main function that calls all functions
"""
clean()
h_choice = '' # X or O
c_choice = '' # X or O
first = '' # if human is the first

# Human chooses X or O to play


while h_choice != 'O' and h_choice != 'X':
try:
print('')
h_choice = input('Choose X or O\nChosen: ').upper()
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')

# Setting computer's choice


if h_choice == 'X':
c_choice = 'O'
else:
c_choice = 'X'

# Human may starts first


clean()
while first != 'Y' and first != 'N':
try:
first = input('First to start?[y/n]: ').upper()
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except (KeyError, ValueError):
print('Bad choice')

# Main loop of this game


while len(empty_cells(board)) > 0 and not game_over(board):
if first == 'N':
ai_turn(c_choice, h_choice)
first = ''

human_turn(c_choice, h_choice)
ai_turn(c_choice, h_choice)

# Game over message


if wins(board, HUMAN):
clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)
print('YOU WIN!')
elif wins(board, COMP):
clean()
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)
print('YOU LOSE!')
else:
clean()
render(board, c_choice, h_choice)
print('DRAW!')

exit()

start_game()

OUTPUT:-
Practical No : 6
A) Write a program to solve Missionaries and Cannibals problem

AIM:-
PYTHON CODE:-
#Python program to illustrate Missionaries & cannibals Problem
#This code is contributed by Sunit Mal
print("\n")
print("\tGame Start\nNow the task is to move all of them to right side of the river")
print("rules:\n1. The boat can carry at most two people\n2. If cannibals num greater than
missionaries then the cannibals would eat the missionaries\n3. The boat cannot cross the river
by itself with no people on board")
lM = 3 #lM = Left side Missionaries number
lC = 3 #lC = Laft side Cannibals number
rM=0 #rM = Right side Missionaries number
rC=0 #rC = Right side cannibals number
userM = 0 #userM = User input for number of missionaries for right to left side
travel
userC = 0 #userC = User input for number of cannibals for right to left travel
k=0
print("\nM M M C C C | --- | \n")
try:
while(True):
while(True):
print("Left side -> right side river travel")
#uM = user input for number of missionaries for left to right travel
#uC = user input for number of cannibals for left to right travel
uM = int(input("Enter number of Missionaries travel => "))
uC = int(input("Enter number of Cannibals travel => "))

if((uM==0)and(uC==0)):
print("Empty travel not possible")
print("Re-enter : ")
elif(((uM+uC) <= 2)and((lM-uM)>=0)and((lC-uC)>=0)):
break
else:
print("Wrong input re-enter : ")
lM = (lM-uM)
lC = (lC-uC)
rM += uM
rC += uC

print("\n")
for i in range(0,lM):
print("M ",end="")
for i in range(0,lC):
print("C ",end="")
print("| --> | ",end="")
for i in range(0,rM):
print("M ",end="")
for i in range(0,rC):
print("C ",end="")
print("\n")

k +=1

if(((lC==3)and (lM == 1))or((lC==3)and(lM==2))or((lC==2)and(lM==1))or((rC==3)and (rM ==


1))or((rC==3)and(rM==2))or((rC==2)and(rM==1))):
print("Cannibals eat missionaries:\nYou lost the game")

break

if((rM+rC) == 6):
print("You won the game : \n\tCongrats")
print("Total attempt")
print(k)
break
except EOFError as e:
print("\nInvalid input please retry !!")
OUTPUT:-
B) Design an application to simulate number puzzle problem

AIM:- Design an application to simulate number puzzle problem

PYTHON CODE:-
# Python3 program to print the path from root
# node to destination node for N*N-1 puzzle
# algorithm using Branch and Bound
# The solution assumes that instance of
# puzzle is solvable

# Importing copy for deepcopy function


import copy

# Importing the heap functions from python


# library for Priority Queue
from heapq import heappush, heappop

# This variable can be changed to change


# the program from 8 puzzle(n=3) to 15
# puzzle(n=4) to 24 puzzle(n=5)...
n=3

# bottom, left, top, right


row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]

# A class for Priority Queue


class priorityQueue:

# Constructor to initialize a
# Priority Queue
def __init__(self):
self.heap = []

# Inserts a new key 'k'


def push(self, k):
heappush(self.heap, k)

# Method to remove minimum element


# from Priority Queue
def pop(self):
return heappop(self.heap)

# Method to know if the Queue is empty


def empty(self):
if not self.heap:
return True
else:
return False

# Node structure
class node:
def __init__(self, parent, mat, empty_tile_pos,
cost, level):

# Stores the parent node of the


# current node helps in tracing
# path when the answer is found
self.parent = parent

# Stores the matrix


self.mat = mat

# Stores the position at which the


# empty space tile exists in the matrix
self.empty_tile_pos = empty_tile_pos

# Stores the number of misplaced tiles


self.cost = cost

# Stores the number of moves so far


self.level = level

# This method is defined so that the


# priority queue is formed based on
# the cost variable of the objects
def __lt__(self, nxt):
return self.cost < nxt.cost

# Function to calculate the number of


# misplaced tiles ie. number of non-blank
# tiles not in their goal position
def calculateCost(mat, final) -> int:

count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1

return count

def newNode(mat, empty_tile_pos, new_empty_tile_pos,


level, parent, final) -> node:

# Copy data from parent matrix to current matrix


new_mat = copy.deepcopy(mat)

# Move tile by 1 position


x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1]
# Set number of misplaced tiles
cost = calculateCost(new_mat, final)

new_node = node(parent, new_mat, new_empty_tile_pos,


cost, level)
return new_node

# Function to print the N x N matrix


def printMatrix(mat):

for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")

print()

# Function to check if (x, y) is a valid


# matrix coordinate
def isSafe(x, y):

return x >= 0 and x < n and y >= 0 and y < n

# Print path from root node to destination node


def printPath(root):

if root == None:
return

printPath(root.parent)
printMatrix(root.mat)
print()

# Function to solve N*N - 1 puzzle algorithm


# using Branch and Bound. empty_tile_pos is
# the blank tile position in the initial state.
def solve(initial, empty_tile_pos, final):

# Create a priority queue to store live


# nodes of search tree
pq = priorityQueue()

# Create the root node


cost = calculateCost(initial, final)
root = node(None, initial,
empty_tile_pos, cost, 0)

# Add root to list of live nodes


pq.push(root)

# Finds a live node with least cost,


# add its children to list of live
# nodes and finally deletes it from
# the list.
while not pq.empty():

# Find a live node with least estimated


# cost and delete it form the list of
# live nodes
minimum = pq.pop()

# If minimum is the answer node


if minimum.cost == 0:

# Print the path from root to


# destination;
printPath(minimum)
return

# Generate all possible children


for i in range(4):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]

if isSafe(new_tile_pos[0], new_tile_pos[1]):

# Create a child node


child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)

# Add child to list of live nodes


pq.push(child)

# Driver Code

# Initial configuration
# Value 0 is used for empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]

# Solvable Final configuration


# Value 0 is used for empty space
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]

# Blank tile coordinates in


# initial configuration
empty_tile_pos = [ 1, 2 ]

# Function call to solve the puzzle


solve(initial, empty_tile_pos, final)
OUTPUT:-

Practical No : 7
A) Write a program to shuffle Deck of cards

AIM:- Program to shuffle Deck of cards

PYTHON CODE:-
import random

deck=[]
suits=["S", "D","C","H"]
ranks= ['2','3','4','5','6','7','8','9','10','J', 'Q', 'K', 'A']

#%=remainder & / = quotient


#make your deck of cards
for i in range (0, 52):
deck.append(ranks[i%13] + suits[int(i/13)])
print(deck)

#shuffle the created deck")


for i in range(0,len(deck)-1):
index= random.randint(0,51)
#print(index)
deck[i],deck[index]= deck[index],deck[i]

print("\ndeck after shuffling")


print(deck)
OUTPUT:-
B) Solve traveling salesman problem using artificial intelligence technique

AIM:- Solve traveling salesman problem using artificial intelligence technique

PYTHON CODE:-
from sys import maxsize
from itertools import permutations
V=4

# implementation of traveling Salesman Problem


def travellingSalesmanProblem(graph, s):

# store all vertex apart from source vertex


vertex = []
for i in range(V):
if i != s:
vertex.append(i)

# store minimum weight Hamiltonian Cycle


min_path = maxsize
next_permutation=permutations(vertex)

for i in next_permutation:
#print("prem", i)
# store current Path weight(cost)
current_pathweight = 0

# compute current path weight


k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]

# update minimum
min_path = min(min_path, current_pathweight)

return min_path

# Driver Code
if __name__ == "__main__":
# matrix representation of graph
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))
OUTPUT:-

Practical No : 8
A) Solve the block of World problem

AIM:- Solve the block of World problem

PYTHON CODE:-
tab = []
result = []
goalList = ["a", "b", "c", "d", "e"]

def parSolution(N):
for i in range(N):
if goalList[i] != result[i]:
return False
return True

def Onblock(index, count):

# break point of recursive call


if count == len(goalList)+1:
return True
# copy tab of index value to result
block = tab[index]
# stack block
result.append(block)
print(result)
if parSolution(count):
print("Pushed a result solution ")
# remove block from tab
tab.remove(block)
Onblock(0, count + 1)
else:
print("result solution not possible, back to the tab")
# pop out if no partial solution
result.pop()
Onblock(index+1, count)

def Ontab(problem):
# check if everything in stack is on the tab
if len(problem) != 0:
tab.append(problem.pop())
Ontab(problem)
# if everything is on the tab the we return true
else:
return True

def goal_stack_planing(problem):
# pop problem and put in tab
Ontab(problem)
# print index and number of blocks on result stack
if Onblock(0, 1):
print(result)

if __name__ == "__main__":
problem = ["c", "a", "e", "d", "b"]
print("Goal Problem")
for k, j in zip(goalList, problem):
print(k+" "+j)
goal_stack_planing(problem)
print("result Solution")
print(result)
OUTPUT:-

B) Solve constraint satisfaction problem


AIM:- Solve constraint satisfaction problem

PYTHON CODE:-
#Install the below given libraries via pip
#pip install simpleai

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


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))
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:-
Practical No : 9
A) Derive the expressions based on Associative law.

AIM:- Derive the expressions based on Associative law.


PYTHON CODE:-
1) Examples of the associative law of addition:

2) examples of the associative law of multiplication: 5*5*6=150 :


B) Derive the expressions based on Distributive law.

AIM:- Multiply everything inside parentheses by what is outside it.


PYTHON CODE:
Example: (5)*(6+2-4)

Practical No : 10

A) Write a program to derive the predicate (for eg: Sachin is batsman, batsman is
cricketer => Sachin is cricketer)

Code:
batsman (sachin)
batsman (msd)
batman (virat)
baller (anilkumble)
baller (harbhajan)
cricketer (x) :- baller(x)
cricketer (x) :- batsman(x)
Output:-
1 ?- baller (x)
x = anilkumble

2 ?- cricketer (x) batsman(x)


x = Sachin

3 ?- batsman (virat)
true
4 ?- baller (virat).
False

B) Write a program which contains three predicates: male, female, parent. Make
rules for following family relations: father, mother, grandfather grandmother
brother, uncle, sister, aunt, nephew & niece, cousin.
Question:
1 Draw family tree.
2 Define: Classes, facts, predicates and rules with conjunction and disjunction.

2: clauses
A prolog program consists of no. of clauses. Each clause is either fact or rule. After a prolog program is
consulted (on loaded). VIN prolog interpreter, users can submit goals or queries, of prolog interpreter
will give result (answers) according to facts and rules.

Facts
A fact must start with a predicate (which is an atom) and end with a full stop. The predicate may be
followed by one or more arguments which are enclosed by parenthesis . The argument can be atoms
(in this case, these atoms are treated as constants), numbers, variables or lists. Arguments are
separated by commas. If we consider the argument in a fact to be objects, then the predicate of the fact
describes a property of an object. In a prolog program, a presence of a fact indicated a statement that
is true. An absence of a fact indicates a statement that is not true.
Predicates
In addition to self-defined predefines, prolog also provides built-in predicates. The following are some
common built-in predicates:

Arithmetic predicates (arithmetic operators):


+,-,*,/ (these operates on numbers and variables) o< (less than) - operates on no. & variables only, o>
(greater than) - operates on nos and variables, o=<(less than or equal to) - operates on no. of variables
only, o>= (greater than or equal to) - operates on nos and variables o is - the operands have same
value o= -the two operands are identical o=\= -two operands do not have same values. Note that each
of the built-in predicate above have two arguments, one on the left of the predicate & another on the
right. However, user-defined predicates must come before their arguments.

Rules:
A rule can be viewed as an extension of a fact with added conditions that also have to be satisfied for it
to be true. It consists of two parts, the first part is similar to fact (a predicate with arguments). The
second part consists of other clauses (fact or rules are separated by commas). which must all be true
for the true itself to be true. these two parts are separated by “:-“. You may interpret this operator as
"if" in English. The comma "," Express conjunction is Prolog. The semicolon ":" Expresses disjunction
in Prolog.

Python Code:
male (ramjibhai)
male (dhirubhai)
male (pravinbhai)
male (hitesh)
male (harsh)
female (shantiben)
female (hansaben)
female (bhartiben)
female (krishna)
female (harshita)
parent (ramjibhai, dhirubhai)
parent (ramjibhai, pravinbhai)
parent (shantiben, dhirubhai)
parent (shantiben, pravinbhai)
parent (dhirubhai, hitesh).parent (dhisubhai, krishna)
parent (hansaben, hitesh).parent (hansaben, krishna)
parent (bhartiben, harsh).parent (bhartiben, harshita)
father (x,y): -male (x), partent (x,y)
mother (x,y):- female(x), parent (x,y)
sister (x,y):- female(x), father (z,x), father (z,y), x\=y
brother (x,y):-male(x), father (z,x), father (z,y), x\=y
cousin (x,y) :- father (z, x), father (w,y), brother(z,w)
grandma (x,y):- father (z,y), mother (x,z)
grandpa (x,y):- father (z,y), father (x,z)
uncle(x,y):- father (z,y), brother (x,z)
aunt (x,y) :- uncle (z,y), father (z,q), mother(x,q)
nephew (x,y):- male (x), father (z,x), brother (y,z)
niece (x, y) :-female (x), father (z,x), brother (y,z)

Output:
? - mother (y,hitesh)
y = hansaben

? - sister(x,hitesh)
x = krishna

? brother(x,hitesh)
False

You might also like