Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
23 views37 pages

Farhan AI

The document outlines a series of practical programming assignments for a TYBSCIT course at Malini Kishor Sanghvi College, focusing on algorithms such as Depth First Search, Breadth First Search, N-Queens, Tower of Hanoi, Alpha-Beta Search, Hill Climbing, A* algorithm, Water Jug problem, and Missionaries and Cannibals problem. Each practical includes aims, Python code snippets, and expected outputs. The assignments are designed to enhance students' understanding of artificial intelligence concepts through hands-on coding experience.

Uploaded by

alhaddadruhaan
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)
23 views37 pages

Farhan AI

The document outlines a series of practical programming assignments for a TYBSCIT course at Malini Kishor Sanghvi College, focusing on algorithms such as Depth First Search, Breadth First Search, N-Queens, Tower of Hanoi, Alpha-Beta Search, Hill Climbing, A* algorithm, Water Jug problem, and Missionaries and Cannibals problem. Each practical includes aims, Python code snippets, and expected outputs. The assignments are designed to enhance students' understanding of artificial intelligence concepts through hands-on coding experience.

Uploaded by

alhaddadruhaan
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/ 37

MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT:-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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

CODE:-

OUTPUT:-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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

DIAGRAM:

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

CODE:-

OUTPUT:-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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.

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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):
print("moving disk from",fp,"to",tp)
moveTower(3,"A","B","C")

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT:-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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.

CODE-
MAX, MIN = 1000, -1000
def minimax(depth, nodeIndex, maximizingPlayer,values, alpha, beta):
if depth == 3:
return values[nodeIndex]
if maximizingPlayer:
best = MIN
for i in range(0, 2):
val = minimax(depth + 1, nodeIndex * 2 + i,False, values, alpha, beta)
best = max(best, val)
alpha = max(alpha, best)
if beta <= alpha:
break
return best
else:
best = MAX
for i in range(0, 2):
val = minimax(depth + 1, nodeIndex * 2 + i,True, values, alpha, beta)
best = min(best, val)
beta = min(beta, best)
if beta <= alpha:
break
return best

if __name__ == "__main__":
values = [8, 5, 2, -6, 3, 1, 0, -7]
print("MARIA LOKHANDWALA-109")
print("The optimal value for alpha-beta serach is :", minimax(0, 0, True, values, MIN,
MAX))

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

AIM:-
Write a program for Hill climbing problem.
DIAGRAM:-

PYTHON CODE:

print("MARIA LOKHANDWALA-109")
SuccList ={ 'A':[['B',3],['C',2]], 'B':[['D',2],['E',3]], 'C':[['F',2],['G',4]], 'D':[['H',1],['I',99]],'F':
[['J',1]],'G':[['K',99],['L',3]]}
Start='A'
Closed = list()
SUCCESS=True
FAILURE=False
def MOVEGEN(N):
New_list=list()
if N in SuccList.keys():
New_list=SuccList[N]
return New_list
def SORT(L):
L.sort(key = lambda x: x[1])
return L
def heu(Node):
return Node[1]
def APPEND(L1,L2):

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

New_list=list(L1)+list(L2)
return New_list
def Hill_Climbing(Start):
global Closed
N=Start
CHILD = MOVEGEN(N)
SORT(CHILD)
N=[Start,5]
print("\nStart=",N)
print("Sorted Child List=",CHILD)
newNode=CHILD[0]
CLOSED=[N]
while (heu(newNode) < heu(N)) and (len(CHILD) !=0):
print("\n--------------------------")
N= newNode
print("N=",N)
CLOSED = APPEND(CLOSED,[N])
CHILD = MOVEGEN(N[0])
SORT(CHILD)
print("Sorted Child List=",CHILD)
print("CLOSED=",CLOSED)
newNode=CHILD[0]
Closed=CLOSED
Hill_Climbing(Start)

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

Practical no-4
A. Write a program to implement A* algorithm.
Aim:-Write a program to implement A* algorithm.
Note:
Install 2 package in python scripts directory using pip command.
1. pip install simpleai
2. pip install pydot flask

STEPS:

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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

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

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT:-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

PRACTICAL NO-5

A. Write a program to solve water jug problem.


Aim:-Write a program to solve water jug problem.

Code:-
from collections import defaultdict
#here x and y arre jug1 and jug2
x, y, aim = 4, 3, 2
visited = defaultdict(lambda: False)
def waterJugSolver(amt1, amt2):
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True
if visited[(amt1, amt2)] == False:
print(amt1, amt2)
visited[(amt1, amt2)] = True
return (
waterJugSolver(0, amt2) or
waterJugSolver(amt1, 0) or
waterJugSolver(x, amt2) or
waterJugSolver(amt1, y) or
waterJugSolver(amt1 + min(amt2,(x-amt1)),amt2 - min(amt2,(x-amt1)))or
waterJugSolver(amt1 - min(amt1,(y-amt2)),amt2 + min(amt1,(y-amt2)))
)

else:
return False
print("Steps: ")
waterJugSolver(0, 0)
print("MARIA LOKHANDWALA-109")

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

Output:-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

PRACTICAL NO.-6
A. Write a program to solve Missionaries and Cannibals problem.

Aim:-Write a program to solve Missionaries and Cannibals problem.


Diagram:-

Python Code:-

#Python program to illustrate Missionaries & cannibals Problem


#This code is contributed by Sunit Mal
print("MARIA LOKHANDWALA")
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
SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE
MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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
while(True):
print("Right side -> Left side river travel")
userM = int(input("Enter number of Missionaries travel => "))
userC = int(input("Enter number of Cannibals travel => "))

if((userM==0)and(userC==0)):
print("Empty travel not possible")
print("Re-enter : ")
elif(((userM+userC) <= 2)and((rM-userM)>=0)and((rC-userC)>=0)):
break
else:
print("Wrong input re-enter : ")
lM += userM
lC += userC
SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE
MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

rM -= userM
rC -= userC

k +=1
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")

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
except EOFError as e:
print("\nInvalid input please retry !!")

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT:

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

Code:-
# Python program to shuffle a deck of card

# importing 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])
print("MARIA LOKHANDWALA-109")

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT:-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

AIM- solve traveling salesman problem using artificial intelligence technique.

CODE-
from sys import maxsize
from itertools import permutations
V=4
def travellingSalesmanProblem(graph, s):
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_pathweight = 0
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
min_path = min(min_path, current_pathweight)
return min_path
if __name__ == "__main__":
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print("travelling sales man path cost:",travellingSalesmanProblem(graph, s))
print("MARIA LOKHANDWALA-109")

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

PRACTICAL NO.-8
A. 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):
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))

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

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

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

B) AIM- Solve the block of world problem.


CODE-

print("MARIA LOKHANDWALA-109")
def bow(n,m,f,t,au):
if(n==1 and m==1):
print("move for 1 box is from place"+f+"to place"+au)
print("move for 2 box is from place"+t+"to place"+f)
print("move for 3 box is from place"+au+"to place"+t)
print("move for 4 box is from place"+f+"to place"+t)

if(n==1):
print("move for 1 box is from place"+f+"to place"+t)
return
if(m==1):
print("move for 1 box is from place"+f+"to place"+t)
return
bow(n-1,m-1,f,au,t)
print("move for"+str(n)+" box is from place"+f+"to place"+t)
bow(n-1,m-1,t,f,au)
print("Enter the no of box in P1:")
n=int(input())
print("Enter the no of box in P2:")
m=int(input())
print("its done!!!!:\n")
bow(n,m,'P1','P3','P2')

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

OUTPUT-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

PRACTICAL NO.-9
A) Aim- .Derive expression based on Associative law

Code-
import random
a=random.randint(0,99)
b=random.randint(0,99)
c=random.randint(0,99)
print("DIST LAW:--->");
print("A+(B+C)->",(a+(b+c)))
print("(A+B)+C->",((a+b)+c))
print("MARIA LOKHANDWALA-109")

OUTPUT-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE


MALINI KISHOR SANGHVI COLLEGE TYBSCIT(SEM V)

B) Aim- .Derive expression based on Distributive law

CODE-

import random
a=random.randint(0,99)
b=random.randint(0,99)
c=random.randint(0,99)
print("DIST LAW:--->");
print("A(B+C)->",(a*(b+c)))
print("(AB)+(AC)->",((a*b)+(a*c)))
print("MARIA LOKHANDWALA-109")

OUTPUT-

SHAIKH MOHD FARHAN 134 ARTIFICIAL INTELLIGENCE

You might also like