Вы находитесь на странице: 1из 115

`

LAB WORKBOOK
18CS2206 ARTIFICIAL INTELLIGENCE

II B.TECH CSE 2019-20 EVEN SEMESTER


K L UNIVERSITY | ARTIFICIAL INTELLIGENCE – 18CS2206
18CS2206 ARTIFICIAL INTELLIGENCE

LABORATORY WORKBOOK

STUDENT NAME
REG. NO
YEAR
SEMESTER
SECTION
FACULTY

1
18CS2206 ARTIFICIAL INTELLIGENCE

Organization of the STUDENT LAB WORKBOOK


The laboratory framework includes a creative element but shifts the time-intensive
aspects outside of the Two-Hour closed laboratory period. Within this structure, each
laboratory includes three parts: Prelab, In-lab, and Postlab.
a. Pre-Lab

The Prelab exercise is a homework assignment that links the lecture with the
laboratory period - typically takes 2 hours to complete. The goal is to synthesize the
information they learn in lecture with material from their textbook to produce a
working piece of software. Prelab Students attending a two-hour closed laboratory
are expected to make a good-faith effort to complete the Prelab exercise before
coming to the lab. Their work need not be perfect, but their effort must be real
(roughly 80 percent correct).
b. In-Lab

The In-lab section takes place during the actual laboratory period. The First hour of
the laboratory period can be used to resolve any problems the students might have
experienced in completing the Prelab exercises. The intent is to give constructive
feedback so that students leave the lab with working Prelab software - a significant
accomplishment on their part. During the second hour, students complete the In-lab
exercise to reinforce the concepts learned in the Prelab. Students leave the lab having
received feedback on their Prelab and In-lab work.
c. Post-Lab

The last phase of each laboratory is a homework assignment that is done following the
laboratory period. In the Postlab, students analyze the efficiency or utility of a given
system call. Each Postlab exercise should take roughly 120 minutes to complete.

2
18CS2206 ARTIFICIAL INTELLIGENCE

2019-20 EVEN SEMESTER LAB CONTINUOUS EVALUATION

Pre Lab In-Lab Post Lab Total Faculty


Sl Viva Voce
Date Experiment Name
No (5M) LOGIC EXECUTION RESULT ANALYSIS (5M) (5M) (50M) Signature
(10M) (10) (10) (5)

10

11

12
18CS2206 ARTIFICIAL INTELLIGENCE

Table of Contents
Organization of the STUDENT LAB WORKBOOK .................................................... 2
Lab Session 01: A Simple Chatter Bot ........................................................................ 5
Lab Session 02: Uninformed Search ..................................................................... 13
Lab Session 03: Travelling Salesman Problem ....................................................... 24
Lab Session 04: Hill Climbing Method ................................................................... 37
Lab Session 05:Alpha beta prunig ........................................................................... 47
Lab Session 06: Hangman game .............................................................................. 56
Lab Session 07:Building Knowledge and reasoning ................................................... 45

4
18CS2206 ARTIFICIAL INTELLIGENCE
Time of the Session: to
Lab Session 01: A Simple Chatter Bot
Date of the Session: / /

Program Title: A Simple Chatter Bot

Pre-requisite: Conditional statements and functions and knowledge on Chatter Bot


Pre Lab:
1 A) Prateek is working on a project and he is slightly poor in mathematics. The project is based on
performing arithmetic and logical operations with numbers. So help him out by writing a Python program
that considers ‘a’ and ‘b’ as input and gives the result of all arithmetic & logical operations as output .Use
different modules for every operation.

Python code:
def arithmetic(n,num1,num2):
if(n==1):
add = num1 + num2
print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
if(n==2):
dif = num1 - num2
print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)
if(n==3):
mul = num1 * num2
print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
if(n==4):
div = num1 / num2
print('Division of ',num1 ,'and' ,num2 ,'is :',div)
if(n==5):
modulus = num1 % num2
print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)
if(n==6):
floor_div = num1 // num2
print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
if(n==7):
5
18CS2206 ARTIFICIAL INTELLIGENCE

power = num1 ** num2


print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)

def binary(n,num1,num2):
if(n==1):
ando = num1 & num2
print('AND of ',num1 ,'and' ,num2 ,'is :',ando)
if(n==2):
oro= num1 | num2
print('OR of ',num1 ,'and' ,num2 ,'is :',oro)
if(n==3):
if not num1 ^ num2:
print('XOR of that numbers is: ',True)

while(True):
print("Enter 1 for arithmetic 2 for logical")
op=int(input("Enter which type of operation you want: "))
if(op==1):
print("1.addtion")
print("2.subtraction")
print("3.Multiplication")
print("4.Division")
print("5.modulo")
print("6.floor division")
print("7.exponent")
opt=int(input("Enter your option number :: "))
num1 = int(input('Enter First number: '))
6
18CS2206 ARTIFICIAL INTELLIGENCE

num2 = int(input('Enter Second number '))


arithmetic(opt,num1,num2)
else:
print("1.AND")
print("2.OR")
print("3.XOR")
i=int(input("Choose your option from above and enter a number: "))
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
binary(i,num1,num2)

7
18CS2206 ARTIFICIAL INTELLIGENCE

Writing space for the Problem:(For Student’s use only)

8
18CS2206 ARTIFICIAL INTELLIGENCE

9
18CS2206 ARTIFICIAL INTELLIGENCE

Writing space for the Problem:(For Student’s use only)

10
18CS2206 ARTIFICIAL INTELLIGENCE
IN LAB:

1 A) Jaswanth is doing a problem in which he has to calculate the LCM and HCF of given numbers. So help
him out by writing a Python code that return LCM and HCF values. Use different modules for both LCM
and HCF.

Python code:
def hcf(a,b):
while b > 0:
a, b = b, a % b
return a

def lcm(a, b):

return a * b / hcf(a, b)

while True:
a=int(input())
b=int(input())
if(a==0 or b==0):
print("Invalid cannot perform the operation")
break
else:
print("HCF of given number is",hcf(a,b))
print("LCM of given number is",lcm(a,b))

11
18CS2206 ARTIFICIAL INTELLIGENCE

11
18CS2206 ARTIFICIAL INTELLIGENCE

1 C) You’re facing many issues with your laptop and you have no idea what’s happening to it .So you need
to send a request by having a conversation with the chat bot of the service company to fix this issue. Based
on the conversation , develop a python code to implement a simple chatter bot using functions (don’t use
modules and packages).For example , if you give “Hi” it must print “Hello”. For every iteration it must take
a new question as input and if you say “Bye”, the loop must be terminated.

def chatbox(msg,name):
a=msg
b=name
a.lower()
if "Hi" in a:
print("Hello")
elif 'How are you' in a :
print("I am fine")
elif 'are you working?' in a:
print("yes. I'am working in KLuniversity as a Professor")
elif 'what is your name?'in a:
print("My name is",b)
elif 'ok'in a:
print("Nice name and Nice meeting you")
elif 'what did you do yesterday?' in a:
print("I have done Coding challenge in codechef")
elif 'bye' in a:
print("Ok bye, Meet you later, Have a good day")
else:
print("I can't able to understand your question")

name1 = input("Enter your friend you would like to chat : ")


print("You may ask any one of these questions")
print("Hi")
print("How are you?")
print("Are you working?")
print("what is your name?")
print("what did you do yesterday?")

while True:
message=input("Type a message here : ")
if(message=='bye'):
print("Ok bye,meet you later!")
break
else:
chatbox(message,name1)

12
18CS2206 ARTIFICIAL INTELLIGENCE

POST LAB :

1 A)The monthly challenge contest is going on in the codechef , an online coding platform. Ram and his
friends are participating in the contest. It is based on printing complex patterns . In order to complete that
, he must know the logic of Pascal’s triangle. So help him by writing a python code to generate a Pascal’s
triangle by taking a number n as an input and generating Pascal triangle with n+1 lines as output.

Python code:

def fact(n):

res=1

for c in range(1,n+1):

res = res*c

return res

rows = int(input("Enter the number of rows : "))

for i in range(0, rows):

for j in range(1, rows-i):

print(" ", end="")

for k in range(0, i+1):

coff = int(fact(i)/(fact(k)*fact(i-k)))

print(" ", coff, end="")

print()

1 B)Abhinav owns a hotel in which a robot is given the task of serving the orders to the respective
13
18CS2206 ARTIFICIAL INTELLIGENCE

customers. Initially, the robot is at coordinate x=X. Then , it should execute a sequence of n number of
commands , described by string(s) with some length(l).If command gives as l it must decrement by 1 ,
else it must increment by 1. Help her by writing a python program (Using functions). Read the length of
the string , x value and string as input.

Python code:

def start():

o = []

for _ in range(int(input())):

n, x = map(int, input().split())

s = input()

d = dict()

d[x] = 1

for c in s:

if c == 'R':

x += 1

else:

x -= 1

d[x] = 1

o.append(len(d))

for x in o:

print(x)

start() //main function

1 C) Ram is assigned to develop a intelligent agent(like a chatterbot) for the addition of two intergers
14
18CS2206 ARTIFICIAL INTELLIGENCE

provided the agent must follow some conditions: the agent work will start with reflex to greeting from user
and continues in his state(prime work addition of two numbers) until user provide agent with stop option.
Python code:

def chat(a,b):

if(a>=0 or b>=0):

print("Addtion of your numbers: ",(a+b))

else:

print("Invalid")

n=input("Enter hi to start your additon chatter: ")

if(n=="Hi" or n== "hi" or n=="HI"):

print("Hello , tell me 2 numbers to perform addition operation")

while(True):

a=int(input("Enter your first number: "))

b=int(input("Enter your second number: "))

chat(a,b)

print("If you want to continue press any key and click enter: ")

n1=input("Enter stop to stop your progress: ")

if(n1=="STOP" or n1=="Stop" or n1=="stop"):

break

15
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

16
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 02: Uninformed Search


Date of the Session: / / Time of the Session: to

Program Title: Water Jug Problem.

Pre-requisite: Searching algorithms


Pre Lab:
2 A) Laxmi is a delivery agent in Flipkart currently being at Arad. He must travel to deliver an order in
Bucharest but he has only limited amount of petrol in his vehicle. So he has to find the shortest distance from
Arad to Bucharest. Analyze the below diagram and give a prototype of the shortest path.

13
18CS2206 ARTIFICIAL INTELLIGENCE

IN LAB:

2 A) A Water Jug Problem: You are given two jugs, a 4-gallon one and a 3-gallon one, a pump which has
unlimited water which you can use to fill the jug, and the ground on which water may be poured. Neither jug
has any measuring markings on it. How can you get exactly 2 gallons of water in the 4-gallon jug?
Let X represent the content of the water in 4-gallon jug.
Let Y represent the content of the water in 3-gallon jug.
Write a program in python to define a set of operators (Rules) that will take us from one state to another:
Start from initial state (X=0, Y=0)
Reach any of the Goal states
(X=2, Y=0)
(X=2, Y=1)
(X=2, Y=2)
(X=2, Y=3)
Find the minimum number of steps to reach any the above mentioned goal states.
print("Water Jug Problem")
x=int(input("Enter X:"))
y=int(input("Enter Y:"))
while True:
rno=int(input("Enter the Rule No"))
if rno==1:
if x<4:x=4
if rno==2:
if y<3:y=3

14
18CS2206 ARTIFICIAL INTELLIGENCE
if rno==5:
if x>0:x=0
if rno==6:
if y>0:y=0
if rno==7:
if x+y>= 4 and y>0:x,y=4,y-(4-x)
if rno==8:
if x+y>=3 and x>0:x,y=x-(3-y),3
if rno==9:
if x+y<=4 and y>0:x,y=x+y,0
if rno==10:
if x+y<=3 and x>0:x,y=0,x+y
print("X =" ,x)
print("Y =" ,y)
if (x==2):
print(" The result is a Goal state")
break
Output:
Water Jug Problem
Enter X:0
Enter Y:0
Enter the Rule No2
X=0
Y=3
Enter the Rule No9
X=3
Y=0
Enter the Rule No2
X=3
Y=3
Enter the Rule No7
X=4
Y=2
Enter the Rule No5
X=0
Y=2

15
18CS2206 ARTIFICIAL INTELLIGENCE
Enter the Rule No9
X=2
Y=0
The result is a Goal state.

16
18CS2206 ARTIFICIAL INTELLIGENCE
Writing space for the Problem:(For Student’s use only)
Post lab:
2 A) A Water Jug Problem: You are given three jugs, a 4-gallon one and a 5-gallon one .a pump which has
unlimited water which you can use to fill the jug, and the ground on which water may be poured. Neither jug
has any measuring markings on it. How can you get exactly 1 gallons of water in the 5-gallon jug?
Let X represent the content of the water in 4-gallon jug.
Let Y represent the content of the water in 5-gallon jug.
Write a program in python to define a set of operators (Rules) that will take us from one state to another:
Start from initial state (X=0, Y=0)
Reach any of the Goal states
(X=1, Y=0)
(X=1, Y=1)
(X=1, Y=2)
(X=1, Y=3)
(X=1, Y=4)
Find the minimum number of steps to reach any the above mentioned goal states.

print("Water Jug Problem")


x=int(input("Enter X:"))
y=int(input("Enter Y:"))
while True:
rno=int(input("Enter the Rule No"))
if rno==1:
if x<4:x=4
if rno==2:
if y<3:y=3

17
18CS2206 ARTIFICIAL INTELLIGENCE
if rno==5:
if x>0:x=0
if rno==6:
if y>0:y=0
if rno==7:
if x+y>= 4 and y>0:x,y=4,y-(4-x)
if rno==8:
if x+y>=3 and x>0:x,y=x-(3-y),3
if rno==9:
if x+y<=4 and y>0:x,y=x+y,0
if rno==10:
if x+y<=3 and x>0:x,y=0,x+y
print("X =" ,x)
print("Y =" ,y)
if (x==2):
print(" The result is a Goal state")
break
Output:
Water Jug Problem
Enter X:0
Enter Y:0
Enter the Rule No2
X=0
Y=3
Enter the Rule No9
X=3
Y=0
Enter the Rule No2
X=3
Y=3
Enter the Rule No7
X=4
Y=2
Enter the Rule No5
X=0
Y=2

18
18CS2206 ARTIFICIAL INTELLIGENCE
Enter the Rule No9
X=2
Y=0
The result is a Goal state.

19
18CS2206 ARTIFICIAL INTELLIGENCE
2 B) Write a python code to implement Depth-First Search by considering the following graph. Your code
must satisfy the graph to find the best and shortest path.

:
A

A)PYTHON CODE:
graph = {
'A': ['B','C'], B C
'B': ['D','E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': [] D E F
}

visited = []
print("STACK:")

def dfs(visited, graph, node):


if node not in visited:
print(node, end=" ")
visited.append(node)
for neighbor in graph[node]:
dfs(visited, graph, neighbor)
dfs(visited, graph, 'A')

OUTPUT:

20
18CS2206 ARTIFICIAL INTELLIGENCE

21
18CS2206 ARTIFICIAL INTELLIGENCE

22
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

23
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 03: Travelling Salesman Problem


Date of the Session: / / Time of the Session: to

Program Title: Travelling Salesman Problem


PRE LAB:
3 A) Describe a state space with 5 states, where the number of nodes visited by iterative deepening search
(including the start node) is S5.

Quick answer: S1 -> S2 -> S3 -> S4 -> S5

More detailed answer:

States: S1, S2, S3, S4, S5.


Root: S1
Child of S1: S2
Child of S2: S3
Child of S3: S4
Child of S4: S5

24
18CS2206 ARTIFICIAL INTELLIGENCE

3 B) ) For the following tree, show the order of nodes visited for breadth-first search, depth-first search,
uniform cost search, and iterative deepening search . The goal node is I and the numbers next to the edges
indicate the associated cost.

Answer

Note: in all methods, after goal node I is visited, the search stops. BFS: ABCDEFGHI
DFS: ABECFGI
UCS: DCBGFEHI

IDS:
first iteration: A
second iteration: ABCD
third iteration: ABECFGDH
fourth iteration: ABECFGI

25
18CS2206 ARTIFICIAL INTELLIGENCE

3 C)Based on below statements write an algorithm:

a. The algorithm starts at the root (assume any node as root node) node and explores as far as
possible along each branch before backtracking.
B . The algorithm starts at the tree root (root node) and explores all of the neighbor nodes at the
present depth prior to moving on to the nodes at the next depth level

BFS: Step 1: SET STATUS = 1 (ready state)


for each node in G
Step 2: Enqueue the starting node A
and set its STATUS = 2
(waiting state)
Step 3: Repeat Steps 4 and 5 until
QUEUE is empty
Step 4: Dequeue a node N. Process it
and set its STATUS = 3
(processed state).
Step 5: Enqueue all the neighbours of
N that are in the ready state
(whose STATUS = 1) and set
their STATUS = 2
(waiting state)
[END OF LOOP]
Step 6: EXIT

DFS: Step 1: SET STATUS = 1 (ready state) for each node in G


Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
Step 5: Push on the stack all the neighbours of N that are in the ready state (whose STATUS = 1) and set
their
STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT

26
18CS2206 ARTIFICIAL INTELLIGENCE

IN LAB:
3 A) There is a sales rep who goes around N urban communities. He needs to visit each city once. The request
for city doesn't make a difference. To head out to a specific city , he needs to cover certain separation. The
sales rep needs to travel each city exactly once and come back to his very own territory. He wishes to travel
keeping the separation as low as could be allowed, with the goal that he could limit the expense and time
factor at the same time. Use the graph given below and write a Python program to satisfy the given conditions.

from sys import maxsize


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

while True:

# store current Path weight(cost)


current_pathweight = 0

# compute current path weight

27
18CS2206 ARTIFICIAL INTELLIGENCE
k=s
for i in range(len(vertex)):
current_pathweight += graph[k][vertex[i]]
k = vertex[i]
current_pathweight += graph[k][s]

# update minimum
min_path = min(min_path, current_pathweight)

if not next_permutation(vertex):
break

return min_path

# next_permutation implementation
def next_permutation(L):

n = len(L)

i=n-2
while i >= 0 and L[i] >= L[i + 1]:
i -= 1

if i == -1:
return False

j=i+1
while j < n and L[j] > L[i]:
j += 1
j -= 1

28
18CS2206 ARTIFICIAL INTELLIGENCE
L[i], L[j] = L[j], L[i]

left = i + 1
right = n - 1

while left < right:


L[left], L[right] = L[right], L[left]
left += 1
right -= 1

return True

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

29
18CS2206 ARTIFICIAL INTELLIGENCE

3 B) Write a program to find the Sum of Manhattan distances between all pairs of points using BFS. The idea
is to use Greedy Approach. First observe, the Manhattan formula can be decomposed into two independent
sums, one for the difference between x coordinates and the second between y coordinates. If we know how
to compute one of them we can use the same method to compute the other.

def distancesum (arr, n):


arr.sort()
res = 0
sum = 0
for i in range(n):
res += (arr[i] * i - sum)
sum += arr[i]

return res

def totaldistancesum( x , y , n ):
return distancesum(x, n) + distancesum(y, n)
x = [ -1, 1, 3, 2 ]
y = [ 5, 6, 5, 3 ]
n = len(x)
print(totaldistancesum(x, y, n) )

30
18CS2206 ARTIFICIAL INTELLIGENCE

POST LAB:

3 A)Write a python code to implement Breadth-First Search by considering the following graphs?

a. b.
A
A

B C
B C D

D E F
E F G H

A) PYTHON CODE:

def BFS(qnode, parents):


result = {}
queue = []
queue.append( (qnode, 0) )

while queue:
print("queue=", queue)
node, dist = queue.pop(0)
result[node] = dist
if node in parents:
for parent in parents[node]:
qmembers = [x[0] for x in queue]
if parent not in result and parent not in qmembers:
queue.append( (parent, dist+1) )
return result

31
18CS2206 ARTIFICIAL INTELLIGENCE
if __name__ :

parents = dict()
parents = {'A': ['B', 'C', 'D'], 'C': ['G', 'H'], 'B': ['E','F'],'D':['C'],'E': ['G']}

print("Breadth-first search:")
dist = BFS('A', parents)
print(dist)

OUTPUT:

32
18CS2206 ARTIFICIAL INTELLIGENCE

3 B) ISRO are planning to send people to the moon. They want them to be from different countries. You
will be given a list of pairs of astronaut ID's. Each pair is made of astronauts from the same country.
Determine how many pairs of astronauts from different countries they can choose from

N, I = list(map(int, sys.stdin.readline().split()))

# Count astronauts from different countries


astronauts = [-1] * N
countries = []

for _ in range(I):
A, B = list(map(int, sys.stdin.readline().split()))

if astronauts[A] > -1 and astronauts[B] > -1:


if astronauts[A] != astronauts[B]:
k = astronauts[B]
countries[astronauts[A]].extend(countries[k])

for i in countries[k]:
astronauts[i] = astronauts[A]
countries[k] = []

elif astronauts[A] > -1 and astronauts[B] == -1:


astronauts[B] = astronauts[A]
countries[astronauts[A]].append(B)

elif astronauts[A] == -1 and astronauts[B] > -1:


astronauts[A] = astronauts[B]
countries[astronauts[B]].append(A)

else:
astronauts[B] = astronauts[A] = len(countries)
countries.append([A, B])
33
18CS2206 ARTIFICIAL INTELLIGENCE

# Count unpaired astronauts

# Count combinations
x = [len(c) for c in countries if c]

# Count the contributions from the unpaired astronauts


triangular_number = lambda n: n * (n + 1) // 2
unpaired = sum(x == -1 for x in astronauts)

total = triangular_number(unpaired - 1)
total += unpaired * sum(x)

for i in range(len(x) - 1):


for j in range(i + 1, len(x)):
total += x[i] * x[j]

print(total)

34
18CS2206 ARTIFICIAL INTELLIGENCE
3 C) There is enthusiastic traveler who visits different cities in his country. There are a total of N cities
numbered from 1 to N. Some cities are connected to each other as well by bidirectional bridges running
over water. He hates to cross those bridges as travelling via transport is expensive. He is standing at city 1
and wants to reach the city N. Find the minimum the number of bridges that he shall have to cross, if he
takes the optimal route

def bfs(graph, source, destination):

distance = 1

visited = [source]

city = graph[source]

while(len(visited) < len(graph)-1):

l = []

if destination in city:

break

for i in city:

if i in visited:

continue

for j in graph[i]:

l.append(j)

visited.append(i)

distance += 1

city = l

return distance

for _ in range(1):

n, m = map(int, input().split())

graph = [[] for ___ in range(n+1)]

for __ in range(m):

u, v = map(int, input().split())

graph[u].append(v)

graph[v].append(u)
35
18CS2206 ARTIFICIAL INTELLIGENCE
print(bfs(graph, 1, n))

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

36
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 04: Hill Climbing Method

Date of the Session: / / Time of the Session: to

Program Title: Implement Hill climbing Algorithm on blocks world problem.


Pre-requisite:
1. A study on Local search Algorithms.
2. knowledge about heuristic function and generate and test algorithm
3. Knowledge About mathematical optimization problems

PRE LAB:
4 A) Actualize Hill climbing calculation with the assistance of arbitrary numbers in python.

best = generate_random_solution()
best_score = evaluate_solution(best)

while True:
print('Best score so far', best_score, 'Solution', best)
new_solution = copy_solution(best)
mutate_solution(new_solution)

score = evaluate(new_solution)
if evaluate(new_solution) < best_score:
best = new_solution
best_score = score

37
18CS2206 ARTIFICIAL INTELLIGENCE
4 B)Discuss below questions briefly
a)Write an algorithm for simple Hill Climbing?
b)How simple hill climbing is different from steepest ascent hill climbing discuss in detail with
graphs ?

Algorithm for Simple Hill Climbing:


Step 1: Evaluate the initial state, if it is goal state then return success and Stop.
Step 2: Loop Until a solution is found or there is no new operator left to apply.
Step 3: Select and apply an operator to the current state.
Step 4: Check new state:
If it is goal state, then return success and quit.
Else if it is better than the current state then assign new state as a current state.
Else if not better than the current state, then return to step2.
Step 5: Exit.

38
18CS2206 ARTIFICIAL INTELLIGENCE

IN LAB:

4 A)Solve the following blocks world problem using DFS and Hill climbing search.

A D
D C
C B
B A
--------- -----------
Initial state Goal state

39
18CS2206 ARTIFICIAL INTELLIGENCE

4 B)Mahesh is a Business man in Vijayawada. He is planning to construct 4 buildings in his land of 1000
acres. He divided his land into 16 plots each of 62.5 acres. He wants his engineers to build those buildings
based on the following restrictions:
None of the buildings should be in
i) Same row
ii) Same column
iii) And should not conflict diagonally(consider all possible diagonals)

Help his engineers to write a python program in order to find out in which plots they should construct
those 4 buildings.

PYTHON CODE:
N=4
ld = [0] * 30
rd = [0] * 30
cl = [0] * 30

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

def solveNQUtil(board, col):

if (col >= N):


return True

for i in range(N):

if ((ld[i - col + N - 1] != 1 and


rd[i + col] != 1) and cl[i] != 1):

board[i][col] = 1
ld[i - col + N - 1] = rd[i + col] = cl[i] = 1

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


return True
board[i][col] = 0
ld[i - col + N - 1] = rd[i + col] = cl[i] = 0

return False
def solveNQ():
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
40
18CS2206 ARTIFICIAL INTELLIGENCE
[0, 0, 0, 0]]
if (solveNQUtil(board, 0) == False):
printf("Solution does not exist")
return False
printSolution(board)
return True
solveNQ()

OUTPUT:

41
18CS2206 ARTIFICIAL INTELLIGENCE

POST LAB:

4 A)Write a Python code for the given graph ,So that the graph should be colored with minimum number of
colors in which no two adjacent vertices are same ?

D D

E
A G

C D

A) PYTHON CODE:

colors = ['Red', 'Blue', 'Green', 'Yellow', 'Black']


states = ['A', 'B', 'C', 'D' , 'E' , 'F' , 'G']
neighbors = {}
neighbors['A'] = ['B', 'F' , 'G']
neighbors['B'] = ['A', 'C' , 'G']
neighbors['C'] = ['B', 'D' , 'G']
neighbors['D'] = ['C', 'E' , 'G']
neighbors['E'] = ['D', 'F' , 'G']
neighbors['F'] = ['A', 'E' , 'G']
neighbors['G'] = ['A', 'B' , 'C' , 'D' , 'E' , 'F']
colors_of_states = {}
def promising(state, color):
for neighbor in neighbors.get(state):
color_of_neighbor = colors_of_states.get(neighbor)
if color_of_neighbor == color:
return False
return True
def get_color_for_state(state):
for color in colors:
if promising(state, color):
return color

def main():
for state in states:
colors_of_states[state] = get_color_for_state(state)
print (colors_of_states)

main()

OUTPUT:
42
18CS2206 ARTIFICIAL INTELLIGENCE

43
18CS2206 ARTIFICIAL INTELLIGENCE

4 B)Implement python code to perform alpha beta pruning on the


following tree?

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

44
18CS2206 ARTIFICIAL INTELLIGENCE

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 = [3, 5, 6, 9, 1, 2, 0, -1]


print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))

45
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

46
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 05:Alpha beta prunig


Date of the Session: / / Time of the Session: to

Program Title : Implement Alpha-beta pruning on below problem


Pre-requisite:
a. knowledge on Alpha-beta pruning and optimization problems
b. knowledge on Simulate annealing
c. knowledge on Genetic algorithm

PRE LAB:

5 A)The search which is equal to minimax search but eliminates the branches that can’t influence the final
decision. Specify which search it is and write an Algorithm to that search

47
18CS2206 ARTIFICIAL INTELLIGENCE

5 B) One aspect of a simulated annealing cooling schedule is the temperature. Discuss the following:
a. What is the effect of having the starting temperature too high or too low?
b. How do you decide on a suitable starting temperature?
c. How do we decide on a final temperature?

48
18CS2206 ARTIFICIAL INTELLIGENCE

IN LAB:
5 A) Vinay is the CEO of a multinational company. He needs to procure an undergraduate from KLU
dependent on specific qualities he needs to have for his employee. HOD gives him a rundown of 8 scores
dependent on character and academics test. He leads the 3 choice rounds dependent on conduct of
representative he needs. He partitions each into 2 individuals. First round he chooses the understudy having
max marks(communication aptitudes). Second Round he selects based on less no of missteps they have
done.In the last round he chooses an understudy dependent on high checks. Help him to plan a code to
choose the best undergraduate .(Note: The number of undergraduates must be in the number of 2 power of
(n)).

Ans) import math

def minimax (curDepth, nodeIndex,


maxTurn, scores,
targetDepth):

if (curDepth == targetDepth):
return scores[nodeIndex]

if (maxTurn):
return max(minimax(curDepth + 1, nodeIndex * 2,
False, scores, targetDepth),
minimax(curDepth + 1, nodeIndex * 2 + 1,
False, scores, targetDepth))

else:
return min(minimax(curDepth + 1, nodeIndex * 2,
True, scores, targetDepth),
minimax(curDepth + 1, nodeIndex * 2 + 1,
True, scores, targetDepth))

scores = []
n=int(input("Enter the value of n:"))
print("Enter the scores of the students:")
for i in range(2**n):
x=int(input())
scores.append(x)

treeDepth = math.log(len(scores), 2)

print("The optimal value is : ", end = "")


print(minimax(0, 0, True, scores, treeDepth))

49
18CS2206 ARTIFICIAL INTELLIGENCE
5 B). Jacob and Oliver are playing chess and it is Jacob's turn. Jacob have found a good move that will
improve his position. Denote this move as 'A'. He continues to look for moves, making sure he hasn't missed
an even better one. Jacob finds a move that appears to be good. Denote this move as 'B'. Jacob then realize
that the move 'B' allows his opponent Oliver to force checkmate in two moves. Thus, Jacob no longer need
to consider any other possible outcomes from playing move 'B', since Jacob know that his opponent can force
a win. Help Jacob to get his optimal move using alpha-beta pruning by using 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)

if name == "main":
alphabeta(None)

50
18CS2206 ARTIFICIAL INTELLIGENCE

POST LAB:

5 A) Alex and newt are playing a game with n stones where Alex always plays first. The two players move
in alternating turns and plays optimally. In a single move a player can remove either 1, 3 or 4 stones from
the pile of stones. If a player is unable to make a move then that player loses the game. Given the number
of stones where n is less than equal to 200, find and print the name of the winner

CODE:

# Python3 program to find winner of

# the game of N stones

MAX = 200

# finds the winning and losing

# states for the 200 stones.

def findStates(position):

# 0 means losing state

# 1 means winning state

position[0] = 0;

position[1] = 1;

position[2] = 0;

position[3] = 1;

position[4] = 1;

position[5] = 1;

position[6] = 1;

position[7] = 0

# find states for other positions


51
18CS2206 ARTIFICIAL INTELLIGENCE

for i in range(8,MAX+1):

if not(position[i - 1]) or not(position[i - 3]) or not(position[i – ]

position[i] = 1;

else:

position[i] = 0;

#driver function

N = 100

position = [0] * (MAX+1)

findStates(position)

if (position[N] == 1):

print("Player 1")

else:

print("Player 2")

52
18CS2206 ARTIFICIAL INTELLIGENCE

5B)Victoria wants to guess her friend's password. She has to guess it from a set of characters
"abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ”
(Including space)
In order to do that she has to generate random strings and also declare a variable that shows the total
number of letters in the guess that match the letter in the same position of the password. Help her by
writing a Python program and use the genetic algorithm technique.

import random
import datetime

geneSet = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"


target = "Hello World"

def generate_parent(length):
genes = []
while len(genes) < length:
sampleSize = min(length - len(genes), len(geneSet))
genes.extend(random.sample(geneSet, sampleSize))
return ''.join(genes)

def get_fitness(guess):
return sum(1 for expected, actual in zip(target, guess)
if expected == actual)

def mutate(parent):
index = random.randrange(0, len(parent))
childGenes = list(parent)
newGene, alternate = random.sample(geneSet, 2)
childGenes[index] = alternate \
if newGene == childGenes[index] \
else newGene
return ''.join(childGenes)

def display(guess):

fitness = get_fitness(guess)
print("{}\t{}".format(fitness , guess))
random.seed()

53
18CS2206 ARTIFICIAL INTELLIGENCE
startTime = datetime.datetime.now()
bestParent = generate_parent(len(target))
bestFitness = get_fitness(bestParent)
display(bestParent)
while True:
child = mutate(bestParent)
childFitness = get_fitness(child)
if bestFitness >= childFitness:
continue

display(child)
if childFitness >= len(bestParent):
break

bestFitness = childFitness
bestParent = child

54
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

55
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 06: Hangman game


Date of the Session: / / Time of the Session: to

Program Title: Implement Hangman game


Pre-requisite: A study on adversarial search algorithms, Constraint Satisfaction problems.

PRE LAB:

6 A)What is the search where we examine the problem which arises when we try to plan ahead of the world
and other agents are planning against us and write its algorithm and provide a code as an example

56
18CS2206 ARTIFICIAL INTELLIGENCE

IN LAB:
6A)Spaceman is a classic word-guessing game. The user should guess the word correctly by entering
alphabets of the user choice. The Program will get input as single alphabet from the user and it will
matchmaking with the alphabets in the original word. If the user given alphabet matches with the alphabet
from the original word then user must guess the remaining alphabets. Once the user successfully found the
word he will be declared as winner otherwise user lose the game. Write a python code using adversarial
search.

39
18CS2206 ARTIFICIAL INTELLIGENCE

6B)Hangman is a word-guessing game. Here user should guess the word correctly by entering alphabets of
the user choice. The Program will get input as single alphabet from the user and it will matchmaking with
the alphabets in the original word. If the user given alphabet matches with the alphabet from the original
word then user must guess the remaining alphabets. Once the user successfully found the word he will be
declared as winner otherwise user lose the game. Write a python code using hill climbing search.
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
import string
fullstring = string.ascii_lowercase
lettersLeft = ''
for letter in fullstring:
if letter not in lettersGuessed:
lettersLeft = lettersLeft + letter
return lettersLeft
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far

40
18CS2206 ARTIFICIAL INTELLIGENCE

'''
wordGuessed = ''
for letter in secretWord:
if letter in lettersGuessed:
wordGuessed = wordGuessed + letter
else:
wordGuessed = wordGuessed + '_ '
return wordGuessed
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
numCorrect = 0
for letter in secretWord:
if letter in lettersGuessed:
numCorrect += 1
else:
return False
return True
def hangman(secretWord):
guessesLeft = 8
lettersGuessed =[]
print('Welcome to the game Hangman!')

41
18CS2206 ARTIFICIAL INTELLIGENCE

print('I am thinking of a word that is ' + str(len(secretWord)) + ' letters long.' )


print('-----------')
while guessesLeft > 0:
if isWordGuessed(secretWord, lettersGuessed):
return print('Congratulations, you won!')
print('You have ' + str(guessesLeft) + ' guesses left.')
print('Available Letters: ' + getAvailableLetters(lettersGuessed))
user_input = input('Please guess a letter: ')
user_input = str(user_input)
user_input = user_input.lower()
if user_input not in lettersGuessed:
lettersGuessed.append(user_input)
if user_input in secretWord:
print("Good guess: " + getGuessedWord(secretWord, lettersGuessed))
print('-----------')
else:
print("Oops! That letter is not in my word: " + getGuessedWord(secretWord, lettersGuessed))
print('-----------')
guessesLeft -= 1
else:
print("Oops! You've already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed))
print('-----------')
return print("Sorry, you ran out of guesses. The word was " + str(secretWord))
hangman('apple')

42
18CS2206 ARTIFICIAL INTELLIGENCE

Output:
Welcome to the game Hangman!
I am thinking of a word that is 5 letters long.
-----------
You have 8 guesses left.
Available Letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: a
Good guess: a_ _ _ _
-----------
You have 8 guesses left.
Available Letters: bcdefghijklmnopqrstuvwxyz
Please guess a letter: p
Good guess: app_ _
-----------
You have 8 guesses left.
Available Letters: bcdefghijklmnoqrstuvwxyz
Please guess a letter: p
Oops! You've already guessed that letter: app_ _
-----------
You have 8 guesses left.
Available Letters: bcdefghijklmnoqrstuvwxyz
Please guess a letter: l
Good guess: appl_
-----------
You have 8 guesses left.
Available Letters: bcdefghijkmnoqrstuvwxyz
Please guess a letter: e

43
18CS2206 ARTIFICIAL INTELLIGENCE

Good guess: apple


-----------
Congratulations, you won!

44
18CS2206 ARTIFICIAL INTELLIGENCE

POST LAB:

6 A)The following problems that can be solved using Constraint Satisfaction Problems (CSP):

Test Case 1: Magic Square ([[1,2,3],[4,5,6],[7,8,9]])


False
This is not a magic square. The numbers in the rows/columns/diagonals do not add up to the same value.
Let’s try another list of lists.

Test Case 2: Magic Square ([[2,7,6],[9,5,1],[4,3,8]])True

• Develop a python program that satisfies below operations.

45
18CS2206 ARTIFICIAL INTELLIGENCE

Output:

def magic_square(matrix):
size=len(matrix[0])
sum_list=[]
for col in range(size): #Vertical sum
sum_list.append(sum(row[col] for row in matrix))
sum_list.extend([sum(lines) for lines in matrix])#Horizontal sum
result1=0
for i in range(0,size):
result1+=matrix[i][i]
sum_list.append(result1)
result2=0
for i in range(size-1,-1,-1):
result2+=matrix[i][i]
sum_list.append(result2)
if len(set(sum_list))>1:
return False
return True

magic_square([[2,7,6],[9,5,1],[4,3,8]])
True

42
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

43
18CS2206 ARTIFICIAL INTELLIGENCE

44
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 07:Building Knowledge and reasoning


Date of the Session: / /
PROGRAM TITLE: Building Knowledge and reasoning
PRE-REQUISITE:

PRE-LAB:
1. What is the order of precedence in propositional logic in AI ?

First Precedence Parenthesis

Second Precedence Negation

Third Precedence Conjunction(AND)

Fourth Precedence Disjunction(OR)

Fifth Precedence Implication

Six Precedence Biconditional

45
18CS2206 ARTIFICIAL INTELLIGENCE

2. List the names of inference rules of propositional

46
18CS2206 ARTIFICIAL INTELLIGENCE

3. Properties of propositional logic ?

A)Satisfiable: A atomic propositional formula is satisfiable if there is an interpretation for which it is true.

1) Tautology: A propositional formula is valid or a tautology it is true for all possible interpretations.
2) Contradiction: A propositional formula is contradictory (unsatisfiable) if there is no interpretation
for which it is true.
3) Contingent: A propositional logic can be contingent which means it can be neither a tautology nor
a contradiction.

4) Difference between predicate logic and first order logic ??

A) Besides the propositional logic, there are other logics as well such as predicate logic and other
modal logics. Propositional logic provides more efficient and scalable algorithms than the other logics.
There are few differences between the propositional logic and first-order logic, some of them are
mentioned below.
• Propositional logic deals with simple declarative propositions, while first-order logic additionally
covers predicates and quantification.
• A proposition is a collection of declarative statements that has either a truth value “true” or a truth
value “false”. While a predicate logic is an expression of one or more variables defined on some
specific domain.

47
18CS2206 ARTIFICIAL INTELLIGENCE

INLAB
1.Write a python code for the following inference rules and facts such that the inference engine generates a
list. Implement the code by using Forward Chaining.
Seed(A) ==> Plant(A).
Plant(A) ==> Fruit(A).
Plant(A),Eating(A) ==> Human(A).
Plant("Mango").
Eating("Mango").
Seed("Sprouts").

Code:
global facts
global rules
rules = True
facts = [["plant","mango"],["eating","mango"],["seed","sprouts"]]
def assert_fact(fact):
global facts
global rules
if not fact in facts:
facts += [fact]
rules = True while rules:
rules = False for A1 in facts:
if A1[0] == "seed":
assert_fact(["plant",A1[1]])
if A1[0] == "plant":
assert_fact(["fruit",A1[1]])
if A1[0] == "plant" and ["eating",A1[1]] in facts: assert_fact(["human",A1[1]])
print(facts)

48
18CS2206 ARTIFICIAL INTELLIGENCE

2. Solve the following


Consider the following axioms:
1.Anyone whom Mary loves is a football star.
2.Any student who does not pass does not play.
1. John is a student.
2. Any student who does not study does not pass.
3. Anyone who does not play is not a football star.
4. (Conclusion) If John does not study, then Mary does not love John.
Sol: ∀ x (LOVES(Mary,x) → STAR(x))
∀ x (STUDENT(x) ∧ ¬ PASS(x) → ¬ PLAY(x))
STUDENT(John)
∀ x (STUDENT(x) ∧ ¬ STUDY(x) → ¬ PASS(x))
∀ x (¬ PLAY(x) → ¬ STAR(x))
¬ STUDY(John) → ¬ LOVES(Mary , John)

49
18CS2206 ARTIFICIAL INTELLIGENCE

POSTLAB
1. After teacher explained about inference topic in propotional logic topic ,then sita gave these
problems to her friend to test her capability . Help her to solve the problems.
1. “If I eat spicy foods, then I have strange dreams.” “I have strange dreams if there is thunder while
I sleep.” “I did not have strange dreams.”
2. “I am dreaming or hallucinating.” “I am not dreaming.” “If I am hallucinating, I see elephants
running down the road.”
Sol: (i)
1. The relevant conclusions are: “I did not eat spicy food” and “There is no thunder while I sleep”.
2. Let the primitive statements be:
1. s, ‘I eat spicy foods’
2. d, ‘I have strange dreams’
3. t, ‘There is thunder while I sleep’
3. Then the premises are translated as: s → d, t → d, and ¬d.
4. And the conclusions: ¬s, ¬t.
5. Steps Reason
s → d premise
¬d premise
¬s Modus Tollens to Steps 1 and 2
t → d premise
¬t Modus Tollens to Steps 4 and 2.
(ii)
1. The relevant conclusion is: “I see elephants running down the road.”.
2. Let the primitive statements be:
1. d, ‘I am dreaming’
2. h, ‘I am hallucinating’
3. e, ‘I see elephants running down the road’
3. Then the premises are translated as: d ∨ h, ¬d, and h → e.
4. And the conclusion: e.
5. Steps Reason
d∨h premise
¬d premise
h rule of disjunctive syllogism to Steps 1 and 2
h→e premise
e Modus Ponens to Steps 4 and 3

50
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

51
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 08: Propositional Logic


Date of the Session:___/___/___ Time of the Session: ___to___

PROGRAM TITLE:

PRE-REQUISITE:
PRE-LAB:
1. Write short notes on knowledge based agent with its architecture , and write the two
functions of KB agent. Give the simple algorithm on its functionality

Knowledge-based agents are those agents who have the capability of maintaining an internal state of
knowledge, reason over that knowledge, update their knowledge after observations and take actions. These
agents can represent the world with some formal representation and act intelligently.

The knowledge-based agent (KBA) take input from the environment by perceiving the environment. The
input is taken by the inference engine of the agent and which also communicate with KB to decide as per
the knowledge store in KB. The learning element of KBA regularly updates the KB by learning new
knowledge.
Algorithm:
function KB-AGENT(percept):
persistent: KB, a knowledge base
t, a counter, initially 0, indicating time
TELL(KB, MAKE-PERCEPT-SENTENCE(percept, t))
Action = ASK(KB, MAKE-ACTION-QUERY(t))
TELL(KB, MAKE-ACTION-SENTENCE(action, t))
t=t+1
return action
Operations:
• Firstly it TELLs the KB what it perceives.
• Secondly, it asks KB what action it should take
• Third agent program TELLS the KB that which action was chosen.

52
18CS2206 ARTIFICIAL INTELLIGENCE

2. Write the BNF grammar representation for propositional logic

A)Sentence → AtomicSentence
ComplexSentence AtomicSentence → True | False | P | Q | R | ...
ComplexSentence → (Sentence )
| Sentence Connective Sentence
|¬ Sentence
Connective → ∧ | ∨ | ⇒ | ⇔ ambiguities are resolved through precedence ¬∧∨⇒⇔ or parentheses
e.g. ¬ P ∨ Q ∧ R ⇒ S is equivalent to (¬ P) ∨ (Q ∧ R)) ⇒ S

53
18CS2206 ARTIFICIAL INTELLIGENCE

INLAB
1. We have an example, you might "know" that "all men are mortal", as in for all(x)(man(x) implies
mortal(x)). Then if you ask a question "is JungKook mortal" as mortal(JungKook)? You are supposed to
write an algorithm to unify that with the rule to get a new question "is JungKook a man" man(JungKook)?
Use this concept to write the algorithm used in solving this.

A) Step. 1: If Ψ1 or Ψ2 is a variable or constant, then:


a) If Ψ1 or Ψ2 are identical, then return NIL.
b) Else if Ψ1is a variable,
a. then if Ψ1 occurs in Ψ2, then return FAILURE
b. Else return { (Ψ2/ Ψ1)}.
c) Else if Ψ2 is a variable,
a. If Ψ2 occurs in Ψ1 then return FAILURE,
b. Else return {( Ψ1/ Ψ2)}.
d) Else return FAILURE.
Step.2:
If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return FAILURE.
Step. 3:
IF Ψ1 and Ψ2 have a different number of arguments, then return FAILURE.
Step. 4:
Set Substitution set(SUBST) to NIL.
Step. 5: For i=1 to the number of elements in Ψ1.
a) Call Unify function with the ith element of Ψ1 and ith element of Ψ2, and put the result into S.
b) If S = failure then returns Failure
c) If S ≠ NIL then do,
a. Apply S to the remainder of both L1 and L2.
b. SUBST= APPEND(S, SUBST).
Step.6: Return SUBST.

54
18CS2206 ARTIFICIAL INTELLIGENCE

1) Write a pyhon to Check satisfiability of a propositional sentence. Returns a model when it succeeds.
Returns {true: true} for trivially true expressions.On setting all_models to True, if given expr is
satisfiable then returns a generator of models. However, if expr is unsatisfiable then returns a
generator containing the single element False.(Use SYMPY)

Sol)
from sympy.abc import A, B
from sympy.logic.inference import satisfiable
satisfiable(A & ~B)
satisfiable(A & ~A)
satisfiable(True)
next(satisfiable(A & ~A, all_models=True))
models = satisfiable((A >> B) & B, all_models=True)
next(models)
next(models)
def use_models(models):
for model in models:
if model:
print(model)
else:
print("UNSAT")
use_models(satisfiable(A >> ~A, all_models=True))
use_models(satisfiable(A ^ A, all_models=True))

55
18CS2206 ARTIFICIAL INTELLIGENCE
POSTLAB

1.After teacher explained about inference topic in proportional logic topic ,then sita gave
these problems to her friend to test her capability . Help her to solve the problems.
1. “If I eat spicy foods, then I have strange dreams.” “I have strange dreams if there is
thunder while I sleep.” “I did not have strange dreams.”
2. “I am dreaming or hallucinating.” “I am not dreaming.” “If I am hallucinating, I see
elephants running down the road.”

56
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

57
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 09:


Date of the Session:___/___/___ Time of the Session: ___to___

PROGRAM TITLE:

PRE-REQUISITE:

1.What is Horn form, can all the proportional logics can convert to Horn form? Explain KB
in Horn normal form? How efficient the inferences in the HNF write propositional symbols
can be?

A. • Horn form: a clause with at most one positive literal.


• Not all sentences in propositional logic can be converted into the Horn form .
KB in Horn normal form:
Three types of propositional statements:
• Rules (~B1 v ~B2......~Bk V A)(~(B1 ⋀ B2 ⋀.....Bk)V A) (B1 ⋀ B2 ⋀.....Bk => A)
• Facts B
• Integrity constraints (~B1 V ~B2 V ... ~Bk)(B1 ⋀ B2 ⋀......Bk => False)
Procedures linear in the size of the KB in the Horn form exist.
• Size of a clause: the number of literals it contains.
• Size of the KB in the HNF: the sum of the sizes of its elements.

Example: A, B,(¬A ∨ ¬B ∨ C), (¬C ∨ D), (¬C ∨ E), (¬E ∨ ¬F ∨ G) (or)


A, B,( A ∧ B ⇒ C), (C ⇒ D), (C ⇒ E), (E ∧ F ⇒ G)

58
18CS2206 ARTIFICIAL INTELLIGENCE

Python Code:

2. Write simple Algorithm of Resolution?

S – a set of clauses
Output:
“S is satisfiable” or “S is not satisfiable”
a. Set S0 := S
b. Suppose Si has already been constructed
c. To construct Si+1, choose a pair of clashing literals and clauses C1,C2 in S (if there are any)
and derive
C := Res(C1,C2)
Si+1 := Si U {C}
d. If C is the empty clause, output “S is not satisfiable”; if Si+1 = Si , output “S is satisfiable”
e. Otherwise, set i := i + 1 and go back to Step 2.
(or)
function PL-Resolution(KB,α) returns true or false
inputs: KB, the knowledge base, a sentence in propositional logic α, the query, a sentence in propositional
logic
clauses ← the set of clauses in the CNF representation of KB ∧ ¬α new ← { }
loop do
for each Ci, Cj in clauses do
resolvents ← PL-Resolve(Ci,Cj )
if resolvents contains the empty clause then return true
new ← new ∪ resolvents
if new ⊆ clauses then return false
clauses ← clauses ∪ new

60
18CS2206 ARTIFICIAL INTELLIGENCE

Python Code:

INLAB

A.,B,C,D and E are five thief’s living on different floors of an apartment consisting of only 5
floors. They escaped from the police and hiding in the same building. The police caught them
but
they they don’t know in which floor they are in.
Here are some clues(Problem statements) to find them:
• A does not live on the top floor.
• B does not live on the bottom floor.
• C does not live on either the top or the bottom floor.
• D lives on a higher floor than does B.
• E does not live on a floor adjacent to C.
• C does not live on a floor adjacent to B.
Write a python code to help the policeman to find out where does everyone live?
Code:
from itertools import permutations

class Names:
A, B, C, D, E = range(5)
seq = [A, B, C, D, E]
strings = &quot;A B C D E&quot;.split()

predicates = [
lambda s: s[Names.A] != len(s)-1,
lambda s: s[Names.B] != 0,
lambda s: s[Names.C] != 0 and s[Names.C] != len(s)-1,
lambda s: s[Names.D] &gt; s[Names.B],
lambda s: abs(s[Names.E] - s[Names.C]) != 1,
lambda s: abs(s[Names.B] - s[Names.C]) != 1];

for sol in permutations(Names.seq):

if all(p(sol) for p in predicates):


print(&quot; &quot;.join(x for x, y in sorted(zip(Names.strings, sol), key=lambda x: x[1])))

61
18CS2206 ARTIFICIAL INTELLIGENCE

Python Code:

62
18CS2206 ARTIFICIAL INTELLIGENCE

Post lab:

1. Consider the following Data log knowledge base:


Facts:
1. parent(Elizabeth , Charles).
2. parent(Philip , Charles).
3. parent(Elizabeth , Anne).
4. parent(Philip , Anne).
5. parent(Charles, William).
6. parent(Charles, harry).
7. female(Elizabeth).
8. male(Philip).
9. male(Charles).
10. female(Anne).
11. male(William).
12. male(harry).
Rules:
13. parent(X,Y) ^ parent(Y,Z) => grandparent(X,Z).
13. grandparent(X,Y) ^ male(X) => grandfather(X,Y).
14. grandparent(X,Y) ^ female(X) => grandmother(X,Y).
15. parent(X,Y) => ancestor(X,Y).
16. parent(X,Y) ^ ancestor(Y,Z) => ancestor(X,Z).

Problem 1

What new facts can be inferred using forward chaining? (You should explain how facts are combined with
the rules to get new facts; e.g.
Combining rule 13 with facts 1 and 5 under the substitution X=philip, Y=charles, Z=william gives the new
fact
17. grandparent(philip,william).
You should not trace through the algorithms given in pseudo-code in the class notes.)

62
18CS2206 ARTIFICIAL INTELLIGENCE

Problem 2

Show how backward chaining can be used to prove the goals:


(A) grandfather(Philip, harry).
(B) ancestor(Elizabeth, William).

63
18CS2206 ARTIFICIAL INTELLIGENCE

64
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

65
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 10:

Date of the Session:___/___/___ Time of the Session: ___to___

PROGRAM TITLE:
+
PRE-REQUISITE:

PRE-LAB:
1. Consider the set of all possible five-card poker hands dealt fairly from a standard deck of fifty-two
cards.
a. How many atomic events are there in the joint probability distribution (i.e., how many five-
card hands are there)?
b. What is the probability of each atomic event?
c. What is the probability of being dealt a royal straight flush? Four of a kind?

Python Code:

1) There are(52/ 5)=(52×51×50×49×48)/(1×2×3×4×5)=2,598,960 possible five-card hands.

2) By the fair-dealing assumption, each of these is equally likely. By axioms 2and3, each hand
therefore occurs with probability 1/2,598,960.

3) There are four hands that are royal straight flushes (one in each suit).By principally, since the events
are mutually exclusive, the probability of a royal straight flush is just the sum of the probabilities of
the atomic events, i.e., 4/2,598,960 =1/649,740. For “four of a kind” events, There are 13possible
“kinds” and for each, the fifth card can be one of 48 possible other cards. The total probability is
therefore (13×48)/2,598,960 = 1/4,165.

66
18CS2206 ARTIFICIAL INTELLIGENCE
INLAB
1.Choosing to put our insight into likelihood to great use, we experience an opening machine with three
freely turning reels, each creating one of the four images BAR, BELL, LEMON, or CHERRY with equivalent
likelihood. The space machine has the accompanying payout plot for a wager of 1 coin (where "?" indicates
that we couldn't care less what comes up for that wheel):
BAR/BAR/BAR pays 21 coins
BELL/BELL/BELL pays 16 coins
LEMON/LEMON/LEMON pays 5 coins
CHERRY/CHERRY/CHERRY pays 3 coins
CHERRY/CHERRY/? pays 2 coins
CHERRY/?/? pays 1 coin
Gauge the mean and middle number of plays you can hope to make until you become penniless, in the
event that you start with 8 coins. You can run a recreation to evaluate this, as opposed to attempting to process
a precise answer. Implement a python code for it.

import random
def trial():
funds = 10
plays = 0
while funds >= 1:
funds -=1
plays += 1
slots = [random.choice( ["bar", "bell", "lemon", "cherry"]) for i in range(3)]
if slots[0] == slots[1]:
if slots[1] == slots[2]:
num_equal = 3
else:
num_equal = 2
else:
num_equal = 1
if slots[0] == "cherry":
funds += num_equal
elif num_equal == 3:
if slots[0] == "bar":
funds += 20
elif slots[0] == "bell":
funds += 15
else:
funds += 5
return plays
def test(trials):
results = [trial() for i in xrange(trials)]
mean = sum(results) / float(trials)
median = sorted(results)[trials/2]
print "%s trials: mean=%s, median=%s" % (trials, mean, median)
test(10000)

67
18CS2206 ARTIFICIAL INTELLIGENCE

2. Implement python program to find the probability of drawing a card that is a Heart, a face card (such as
Jacks, Queens, or Kings), or a combination of both, such as a Queen of Hearts

def event_probability(event_outcomes, sample_space):


probability = (event_outcomes / sample_space) * 100
return round(probability, 1)
cards = 52
hearts = 13
heart_probability = event_probability(hearts, cards)
face_cards = 12
face_card_probability = event_probability(face_cards, cards)
queen_of_hearts = 1
queen_of_hearts_probability = event_probability(queen_of_hearts, cards)
print(str(heart_probability) + '%')
print(str(face_card_probability) + '%')
print(str(queen_of_hearts_probability) + '%')

68
18CS2206 ARTIFICIAL INTELLIGENCE

POSTLAB
Write a Python program to implement Kalman filtering to track the position x and velocity v of an aircraft.
Consider the initial observations as follows
x observations = [4000, 4260, 4550, 4860, 5110]
v observations = [280, 282, 285, 286, 290]
Hint : Eliminate the off-diagonal values for simpilification.
CODE :

import numpy as np
from numpy.linalg import inv

x_observations = np.array([4000, 4260, 4550, 4860, 5110])


v_observations = np.array([280, 282, 285, 286, 290])

z = np.c_[x_observations, v_observations]

# Initial Conditions
a = 2 # Acceleration
v = 280
t = 1 # Difference in time

# Process / Estimation Errors


error_est_x = 20
error_est_v = 5

# Observation Errors
error_obs_x = 25 # Uncertainty in the measurement
error_obs_v = 6

def prediction2d(x, v, t, a):


A = np.array([[1, t],
[0, 1]])
X = np.array([[x],
[v]])
B = np.array([[0.5 * t ** 2],
[t]])
X_prime = A.dot(X) + B.dot(a)
return X_prime

def covariance2d(sigma1, sigma2):


cov1_2 = sigma1 * sigma2
cov2_1 = sigma2 * sigma1
cov_matrix = np.array([[sigma1 ** 2, cov1_2],
[cov2_1, sigma2 ** 2]])
return np.diag(np.diag(cov_matrix))

# Initial Estimation Covariance Matrix


P = covariance2d(error_est_x, error_est_v)
69
18CS2206 ARTIFICIAL INTELLIGENCE
A = np.array([[1, t],
[0, 1]])

# Initial State Matrix


X = np.array([[z[0][0]],
[v]])
n = len(z[0])

for data in z[1:]:


X = prediction2d(X[0][0], X[1][0], t, a)
# To simplify the problem, professor
# set off-diagonal terms to 0.
P = np.diag(np.diag(A.dot(P).dot(A.T)))

# Calculating the Kalman Gain


H = np.identity(n)
R = covariance2d(error_obs_x, error_obs_v)
S = H.dot(P).dot(H.T) + R
K = P.dot(H).dot(inv(S))

# Reshape the new data into the measurement space.


Y = H.dot(data).reshape(n, -1)

# Update the State Matrix


# Combination of the predicted state, measured values, covariance matrix and Kalman Gain
X = X + K.dot(Y - H.dot(X))

# Update Process Covariance Matrix


P = (np.identity(len(K)) - K.dot(H)).dot(P)

print("Kalman Filter State Matrix:\n", X)

______________________________________________________________________________________
_____________________

OUTPUT :

Kalman Filter State Matrix:


[[5127.05898493]
[ 288.55147059]]

70
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

71
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 11:

Date of the Session:___/___/___ Time of the Session: ___to___

PROGRAM TITLE:

PRE-REQUISITE:

PRELAB:
1. Write a short note on Uncertainty, reasons for uncertainity
A:

Till now, we have learned knowledge representation using first-order logic and propositional logic with
certainty, which means we were sure about the predicates. With this knowledge representation, we might
write A→B, which means if A is true then B is true, but consider a situation where we are not sure about
whether A is true or not then we cannot express this statement, this situation is called uncertainty

72
18CS2206 ARTIFICIAL INTELLIGENCE

2. Sravan wants to go movie this weekend . His neighbour Rohan (is the one Sravan was hoping to ask out
since long time) is also planing to go to the movie this weekend. The probability that it will rain this
weekend is p1. There are two possible ways to reach the movie spot (bus or train). The probability that
Sravan will take the bus is p2 and that Rohan will take the bus is p3. Travel plans of both are independent
of each other and rain.What is the probability prs that Sravan and Rohan meet each other only (should not
meet in bus or train) in a setup (on a home in rain)?

p2 = float(input())
p3 = float(input())
p1 = float(input())
pres = p1*(p3*(1-p2)+p2*(1-p3))
print('%.6f' %pres)

73
18CS2206 ARTIFICIAL INTELLIGENCE

INLAB
1. The top is PC Computer A, the following 2 are Computer B and C, and the last 4 are Computer BD, BE,
and CD, CE. You are attempting to discover the likelihood that if PC A gets tainted with an infection what
is the likelihood that B or C gets contaminated with an infection. What's more, if B or C gets tainted what is
the likelihood that BD, BE, CD, CE gets contaminated with a virus. You need to run 100 preliminaries to
discover the appropriate response.

aa

ab cc

bbd dbe ecd dce

import random, time

virus_probabilities= { "CompA" : 0.50, "CompB" : .25, "CompC" : .25, "CompBD" : .125,


"CompBE" : .125, "CompCD" : .125, "CompCE" : .125}

def check_probability(computer_name, n_repetitions = 100):


prob_comp, repetitions = 0, 0
p_computer = virus_probabilities[computer_name]
while repetitions < n_repetitions:
x = random.random()
if x <= p_computer:
prob_comp += 1
repetitions += 1
print ("{0} % chance of getting virus on {1}".format(round(prob_comp/100.0, 2), computer_name))

for key in virus_probabilities:


check_probability(key, 1000)

74
18CS2206 ARTIFICIAL INTELLIGENCE

2. Consider a human population that may or may not have cancer (Cancer is True or False) and a medical
test that returns positive or negative for detecting cancer (Test is Positive or Negative), e.g. like a
mammogram for detecting breast cancer.If a randomly selected patient has the test and it comes back positive,
what is the probability that the patient has cancer? Implement an python program to demonstrate Bayes
theorem for the above one . you have provided with the following information.
Sensitivity: 85% of people with cancer will get a positive test result.
Base Rate: 0.02% of people have cancer.
Specificity: 95% of people without cancer will get a negative test result

def bayes_theorem(p_a, p_b_given_a, p_b_given_not_a):


not_a = 1 - p_a
p_b = p_b_given_a * p_a + p_b_given_not_a * not_a
p_a_given_b = (p_b_given_a * p_a) / p_b
return p_a_given_b

p_a = 0.0002
p_b_given_a = 0.85
p_b_given_not_a = 0.05
result = bayes_theorem(p_a, p_b_given_a, p_b_given_not_a)
print('P(A|B) = %.3f%%' % (result * 100))

75
18CS2206 ARTIFICIAL INTELLIGENCE

POSTLAB
1. Let us assume the whether conditions in Vijayawada( i.e, state space) as {S,R}.let us assume the
probability of being sunny and continue to be sunny is 0.3,the probability of changing whether from sunny
to rainy is 0.5,sudenly the whether changes then the probability of being rainy is 0.7 and the probability of
changing whether from rainy to sunny is 0.2.The above data can be represented in transition matrix as
shown below:
S R
S 0.3 0.5
R 0.2 0.7
Assuming the transition matrix does not change, write the python code for finding the probability of being
sunny or rainy at the end of 1st, 2nd and 3rd hours and also represent the transition matrix
diagrammatically.

A) DIAGRAMATIC REPRESENTATION:

PYTHON CODE:
import numpy as np
#Current state
I = np.matrix([[1, 0]])
#Transition Matrix
T = np.matrix([[.3, 0.5],
[.2, 0.7]])
T1 = I * T
# After 1 hours
print("After one hour:")
print (T1)
T2 = T1 * T
# After 2 hours
print("After two hours:")
print (T2)
T3 = T2 * T
# After 3 hours
print("After three hours:")
76
18CS2206 ARTIFICIAL INTELLIGENCE
print (T3)
OUTPUT:

77
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

78
18CS2206 ARTIFICIAL INTELLIGENCE

79
18CS2206 ARTIFICIAL INTELLIGENCE

Lab Session 12:

Date of the Session:___/___/___ Time of the Session: ___to___

PROGRAM TITLE:
PRE-REQUISITE:

PRELAB
1.) What is HMM(Hidden Markov Model)? What is hidden it? Draw a state diagram
for HMM as general case and show how you can write a transition matrix ?
(i) A Hidden Markov Model (HMM) is a statistical Markov model where a system to be
modelled is assumed as a Markov Process with unobserved or hidden states.
(ii) A strategy which make use of stochastic model of speech production is known as
Hidden Markov Model (HMM). It is found to offer performance comparable to time
warping at a function of the computational cost.
(iv) This model has been explored by many researchers. In the case of HMM, a model is
cap3le of being in only in a finite number of difference states.
(v) HMM for speech recognition will have each state cap3le of generating finite number of
possible outputs.
(vi) In generating a word, the system passes from one state to another. Each state emits an
output until the entire word is out. Such a model is illustrated in the figure below. It is called
the state transition diagram.
(vii) In the case of regular Markov Model, the state is directly visible to the observer and
therefore the state transition probabilities are consider as only parameter.

80
18CS2206 ARTIFICIAL INTELLIGENCE

81
18CS2206 ARTIFICIAL INTELLIGENCE

Transition matrix is :

INLAB
1. Sravan has to go airport on time in morning. His general mode of transport is by car and
on a regular day (no car trouble) the probability that he will reach on time is p1. The
probability that he might have car trouble is p2. If the car runs into trouble he will have to
take a train and only 2 trains out of the available N trains will get him to office on time.
Inputs are p1,p2,N

p1=float(input())
p2=float(input())
n=float(input())
a=(1-p1)*p2+(p1*(2/n))
b=float(a*(10**7))
r=b%10
if r>=5:
b+=10
b/=10
print("0."+str(int(b)))

82
18CS2206 ARTIFICIAL INTELLIGENCE

83
18CS2206 ARTIFICIAL INTELLIGENCE

Output:

84
18CS2206 ARTIFICIAL INTELLIGENCE

Students Signature
(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation

Marks Secured: out of

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

85
18CS2206 ARTIFICIAL INTELLIGENCE

86
18CS2206 ARTIFICIAL INTELLIGENCE

87

Вам также может понравиться