Modified Ai File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Artificial Intelligence Shravani Gole [T.22.

125]

Practical No.1

Aim: Implement depth first search algorithm

Source Code:
graph1 = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'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:

1
Artificial Intelligence Shravani Gole [T.22.125]

Aim: Implement breadth first search algorithm

Source Code:
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',]),

def bfs(start):

queue = [start]

levels={}

levels[start]=0

visited = set(start)

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)

return visited

print(str(bfs('a')))

Output:
2
Artificial Intelligence Shravani Gole [T.22.125]

3
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.2

Aim: Simulate 4-Queen / N-Queen problem.

Source Code:
global N

N=4

def printSolution(board):

for i in range(N):

for j in range(N):

print(board[i][j],end=' ')

print()

def isQSafe(board,row,col):

for i in range(col):

if board[row][i]==1:

return False

for i,j in zip(range(row,-1,-1), range(col,-1,-1)):

if board[i][j]==1:

return False

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

if col>=N:

return True
4
Artificial Intelligence Shravani Gole [T.22.125]

for i in range(N):

if isQSafe(board,i,col):

board[i][col]=1

if solveNQUtil(board,col+1)==True:

return True

board[i][col]=0

return False

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

solveNQ()

Output:

5
Artificial Intelligence Shravani Gole [T.22.125]

6
Artificial Intelligence Shravani Gole [T.22.125]

Aim: Solve Tower of Hanoi problem

Source Code:
def moveTower(height,start, aux,end):

if height >= 1;

moveTower(height-1,start,end,aux)

print(“moving disk from”,height, start,”to”,end)

moveTower(height-1,aux,start,end)

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

Output:

7
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.3

Aim: Implement hill climbing problem

Source Code:
SuccList = {'A':[['B',3],['C',2]], 'B':[['D',2],['E',3]], 'C':[['F',2],['G',4]], 'D':[['H',1],['I',9]],
'F':[['J',1]], 'G':[['K',9],['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):

New_list=list(L1)+list(L2)

8
Artificial Intelligence Shravani Gole [T.22.125]

return New_list

def Hill_Climbing(Start):

global Closed

N=Start

CHILD=MOVEGEN(N)

SORT(CHILD)

N=[Start,5]

print("\n Start=",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]

Hill_Climbing(Start)

Output:

9
Artificial Intelligence Shravani Gole [T.22.125]

10
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.4

Aim: Implement A* algorithm

Source Code:
Graph_nodes={

'A':[('B',6),('F',3)],

'B':[('C',3),('D',2)],

'C':[('D',1),('E',5)],

'D':[('C',1),('E',8)],

'E':[('I',5),('J',5)],

'F':[('G',1),('H',7)],

'G':[('I',3)],

'H':[('I',2)],

'I':[('E',5),('J',3)] }

def get_neighbors(v):

if v in Graph_nodes:

return Graph_nodes[v]

else:

return None

def h(n):

H_dist={

'A':10,

'B':8,
11
Artificial Intelligence Shravani Gole [T.22.125]

'C':5,

'D':7,

'E':3,

'F':6,

'G':5,

'H':3,

'I':1,

'J':0}

return H_dist[n]

def aStarAlgo(start_node,stop_node):

open_set=set(start_node) #nodes which is currently visited

closed_set=set()#already visited nodes

g={}

parents={}#parent nodes

g[start_node]=0#distance of current node till latest visited node

parents[start_node]=start_node

while len(open_set)>0:

n=None

for v in open_set:

if n==None or g[v]+h(v)<g[n]+h(n):

n=v

if n==stop_node or Graph_nodes[n]==None:

12
Artificial Intelligence Shravani Gole [T.22.125]

pass

else:

for (m,weight ) in get_neighbors(n):

if m not in open_set and m not in closed_set:

open_set.add(m)

parents[m]=n

g[m]=g[n]+weight

#print(g[m]) calculates total weight of the visited nodes and only takes less than
value after first visit

if n==stop_node:

path=[]

while parents[n]!=n: #checks if current node is parent of its self like A

path.append(n)

n=parents[n]

path.append(start_node)

path.reverse()

print('path found: {}'.format(path))

return path

open_set.remove(n)

closed_set.add(n)

print('path does not exist!')

return None

13
Artificial Intelligence Shravani Gole [T.22.125]

aStarAlgo('A','J')

Output:

14
Artificial Intelligence Shravani Gole [T.22.125]

Aim: Solve Water Jug Problem

Source Code:
j1 = int(input("capacity of jug 1: "))

j2 = int(input("capacity of jug 2: "))

q=int(input("amount of water to be measured"))

def apply_rule(ch,x,y):

if ch==1:

if x<j1:

return j1,y

else:

print("rule cannot be applied")

return x,y

elif ch==2:

if y<j2:

return x,j2

else:

print("rule cannot be applied")

return x,y

elif ch==3:

if x>0 and x+y<=j2:

return 0,x+y

else:

print("rule cannot be applied")

return x,y

15
Artificial Intelligence Shravani Gole [T.22.125]

elif ch==4:

if y>0 and x+y<=j1:

return x+y,0

else:

print("rule cannot be applied")

return x,y

elif ch==5:

if x>0 and x+y>=j2:

return x-(j2-y),j2

else:

print("rule cannot be applied")

return x,y

elif ch==6:

if y>0 and x+y>=j1:

return j1,y-(j1-x)

else:

print("rule cannot be applied")

return x,y

elif ch==7:

if x>0:

return 0,y

else:

print("rule cannot be applied")

return x,y

elif ch==8:

if y>0:

return 0,x+y

16
Artificial Intelligence Shravani Gole [T.22.125]

else:

print("rule cannot be applied")

return x,y

x=y=0

while True:

if x==q or y==q:

print('goal achieved')

break

else:

print("rule 1:fill jug 1")

print("rule 2:fill jug 2")

print("rule 3:transfer all water from jug1 to jug2")

print("rule 4:transfer all water from jug2 to jug1")

print("rule 5:transfer all water from jug1 to jug2 until jug2 is full")

print("rule 6:transfer all water from jug2 to jug1 until jug1 is full")

print("rule 7:empty jug1")

print("rule 8:empty jug2")

ch=int(input("enter rule to apply:"))

x,y=apply_rule(ch,x,y)

print("status")

print("current status:",x,y)

Output:

17
Artificial Intelligence Shravani Gole [T.22.125]

18
Artificial Intelligence Shravani Gole [T.22.125]

19
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.5

Aim: Simulate tic – tac – toe game using min-max algorithm.

Source Code:
import os

import time

board=[' ',' ',' ',' ',' ',' ' ,' ' ,' ' ,' ' ,' ' ]

player=1

#win flag#

win=1

draw=-1

running=0

stop=1

game=running

mark='X'

#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("___|___|___")

20
Artificial Intelligence Shravani Gole [T.22.125]

print(" %c | %c | %c " %(board[7],board[8],board[9]))

print(" | | ")

#func. chks pos is empty or not

def CheckPosition(x):

if(board[x] == ' '):

return True

else:

return False

#func. checks player has won or not

def CheckWin():

global game

#Horizontal winning cond.

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

elif(board[7] == board[8] and board[8] == board[9] and board[7] != ' '):

game = win

#vertical winning cond.

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

21
Artificial Intelligence Shravani Gole [T.22.125]

elif(board[3] == board[6] and board[6] == board[9] and board[3] != ' '):

game = win

#diagonal winning cond.

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

#tie

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[0]\n")

print()

print()

print("please wait........")

time.sleep(1)

while(game==running):

os.system('cls')

drawboard()

if(player%2!=0):

print("player 1's chance")

mark='X'

22
Artificial Intelligence Shravani Gole [T.22.125]

else:

print("Player 2's chance")

mark='0'

choice=int(input("Enter the position between[1-9] where u want to mark:"))

if(CheckPosition(choice)):

board[choice]=mark

player+=1

CheckWin()

os.system('cls')

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

Output:

23
Artificial Intelligence Shravani Gole [T.22.125]

24
Artificial Intelligence Shravani Gole [T.22.125]

Aim: Shuffle deck of cards

Source Code:
import random,itertools

deck=list(itertools.product(range(1,14),["Heart","Spade","club","diamond"]))

random.shuffle((deck))

print(deck)

for i in range(5):

print(deck[i][0],"of",deck[i][1])

Output:

25
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.6

Aim: Design an application to simulate number puzzle problem.

Source Code:
def print_in_format(matrix):

for i in range(9):

if i%3==0 and i>0:

print("")

print(str(matrix[i])+ " ",end = "" )

def count(s):

c= 0

ideal = [1, 2, 3,

4, 5, 6,

7, 8, 0]

for i in range(9):

if s [i] !=0 and s [i] !=ideal [i]:

c+=1

return c

def move(ar,p,st):

store_st = st.copy()

for i in range(len(ar)):

dup1_st = st.copy()

tmp = dup1_st[p]

dup1_st[p] = dup1_st[ar[i]]

dup1_st[ar[i]] = tmp

trh = count(dup1_st)

26
Artificial Intelligence Shravani Gole [T.22.125]

store_st = dup1_st.copy()

return store_st, trh

state = [1, 2, 3,

0, 5, 6,

4, 7, 8]

h = count(state)

Level = 1

print("\n-----------Level "+str(Level)+" ----------- ")

print_in_format(state)

print("\nHeuristic Value (Misplaced) :"+str(h))

while h>0:

pos = int(state.index(0))

print('pos',pos)

Level += 1

if pos == 0:

arr =[1,3]

state, h = move(arr,pos,state)

elif pos == 1:

arr =[0,2,4]

state, h = move(arr,pos,state)

elif pos == 2:

arr =[1,5]

state, h = move(arr,pos,state)

elif pos == 3:

arr =[0,4,6]

27
Artificial Intelligence Shravani Gole [T.22.125]

print(arr)

state, h = move(arr,pos,state)

elif pos == 4:

arr =[1,3,5,7]

state, h = move(arr,pos,state)

elif pos == 5:

arr =[2,4,8]

state, h = move(arr,pos,state)

elif pos == 6:

arr =[3,7]

state, h = move(arr,pos,state)

elif pos == 7:

arr =[4,6,8]

state, h = move(arr,pos,state)

elif pos == 8:

arr =[5,6]

state, h = move(arr,pos,state)

print("\n-----------Level "+str(Level)+" ----------- ")

print_in_format(state)

print("\nHeuristic Value (Misplaced) :"+str(h))

Output:

28
Artificial Intelligence Shravani Gole [T.22.125]

29
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.7

Aim: Solve constraint satisfaction problem

Source Code:
from simpleai.search import CspProblem, backtrack

variables=('A','B','C','D')

domains={

'A':['Red','Green','Blue'],

'B':['Red','Green','Blue'],

'C':['Red','Green','Blue'],

'D':['Red','Green','Blue'],

def different_colors(variables,values):

return values[0] != values[1]

constraints=[

(('A','B'),different_colors),

(('A','C'),different_colors),

(('A','D'),different_colors),

(('B','C'),different_colors),

(('C','D'),different_colors),

30
Artificial Intelligence Shravani Gole [T.22.125]

problem=CspProblem(variables,domains,constraints)

solution=backtrack(problem)

print("Solution:")

print(solution)

Output:

31
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.8

Aim: Derive the expressions based on Associative Law.

Source Code:
associative_law(A, B, C, Result1, Result2) :-

Result1 is A + (B + C) ,

Result2 is (A + B) + C.

%Define some example expressions

expression1(2,3,4).

expression2(5,6,7).

%Derive the results using the associative law

derive_results :-

expression1(A, B, C) ,

associative_law(A, B, C, Result1A, Result2A) ,

expression2(X, Y, Z) ,

associative_law(X, Y, Z, Result1B, Result2B) ,

write('Result of expression 1 using associative law is : ') , nl ,

write('A + (B + C) = ') , write(Result1A) , nl ,

write('(A + B) + C = ') , write(Result2A) , nl ,

write('Result of expression 2 using associative law is : ') , nl ,

write('X + (Y + Z) = ') , write(Result1B) , nl ,

write('(X + Y) + Z = ') , write(Result2B) , nl

32
Artificial Intelligence Shravani Gole [T.22.125]

Output:

33
Artificial Intelligence Shravani Gole [T.22.125]

Aim: Derive the expressions based on Distributive Law.

Source Code:
distributive_law(A, B, C, Result1, Result2) :-

Result1 is A * (B + C) ,

Result2 is A * B + A * C.

%Define some example expressions

expression1(2,3,4).

expression2(5,6,7).

%Derive the results using the associative law

derive_results :-

expression1(A, B, C) ,

distributive_law(A, B, C, Result1A, Result2A) ,

expression2(X, Y, Z) ,

distributive_law(X, Y, Z, Result1B, Result2B) ,

write('Result of expression 1 using distributive law is : ') , nl ,

write('A * (B + C) = ') , write(Result1A) , nl ,

write('A * B + A * C = ') , write(Result2A) , nl ,

write('Result of expression 2 using distributive law is : ') , nl ,

write('X * (Y + Z) = ') , write(Result1B) , nl ,

write('X * Y + X * Z = ') , write(Result2B) , nl .

Output:

34
Artificial Intelligence Shravani Gole [T.22.125]

35
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.9

Aim: Derive the predicate. (for e.g.: Sachin is batsman, batsman is cricketer)
- > Sachin is Cricketer

Source Code:
% Facts
batsman(sachin).
wicketkeeper(dhoni).
footballer(ronaldo).

% Rules
cricketer(X) :- batsman(X).
cricketer(X) :- wicketkeeper(X).

% Footballers are not cricketers


not_cricketer(X) :- footballer(X).

% To determine if someone is a cricketer


is_cricketer(X) :- cricketer(X), \+ not_cricketer(X).

Output:

36
Artificial Intelligence Shravani Gole [T.22.125]

Practical No.10

Aim: Write a program which contains three predicates: male, female, parent. Make rules for
following family relations: father, mother, grandfather, grandmother, brother, sister, uncle,
aunt, nephew and niece, cousin.

Question: i. Draw Family Tree. ii. Define: Clauses, Facts, Predicates and Rules with
conjunction and disjunction

Source Code:
female(pam).

female(liz).

female(pat).

female(ann).

male(jim).

male(bob).

male(tom).

male(peter).

parent(pam,bob).

parent(tom,bob).

parent(tom,liz).

parent(bob,ann).

parent(pat,jim).

parent(bob,peter).

parent(peter,jim).

mother(X,Y):-parent(X, Y),female(X).

father(X, Y):-parent(X,Y),male(X).

sister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\==Y.

brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.

grandparent(X,Y):-parent(X,Z),parent(Z, Y).

37
Artificial Intelligence Shravani Gole [T.22.125]

grandmother(X,Z):-mother(X,Y),parent(Y,Z).

grandfather(X,Z):-father(X, Y),parent(Y,Z).

wife(X,Y):-parent(X,Z),parent(Y,Z),female(X),male(Y).

uncle(X,Z):-brother(X,Y),parent(Y,Z).

Output:

38

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy