Ai A PDF
Ai A PDF
Ai A PDF
LAB WORKBOOK
18CS2206 ARTIFICIAL INTELLIGENCE
LABORATORY WORKBOOK
STUDENT NAME
REG. NO
YEAR
SEMESTER
SECTION
FACULTY
1
18CS2206 ARTIFICIAL INTELLIGENCE
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
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: / /
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
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
7
18CS2206 ARTIFICIAL INTELLIGENCE
8
18CS2206 ARTIFICIAL INTELLIGENCE
9
18CS2206 ARTIFICIAL INTELLIGENCE
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
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")
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
coff = int(fact(i)/(fact(k)*fact(i-k)))
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)
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):
else:
print("Invalid")
while(True):
chat(a,b)
print("If you want to continue press any key and click enter: ")
break
15
18CS2206 ARTIFICIAL INTELLIGENCE
Students Signature
(For Evaluator’s use only)
16
18CS2206 ARTIFICIAL INTELLIGENCE
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.
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:")
OUTPUT:
20
18CS2206 ARTIFICIAL INTELLIGENCE
21
18CS2206 ARTIFICIAL INTELLIGENCE
22
18CS2206 ARTIFICIAL INTELLIGENCE
Students Signature
(For Evaluator’s use only)
23
18CS2206 ARTIFICIAL INTELLIGENCE
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
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
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.
while True:
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
return True
# Driver Code
if name == "__main__":
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.
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:
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()))
for _ in range(I):
A, B = list(map(int, sys.stdin.readline().split()))
for i in countries[k]:
astronauts[i] = astronauts[A]
countries[k] = []
else:
astronauts[B] = astronauts[A] = len(countries)
countries.append([A, B])
33
18CS2206 ARTIFICIAL INTELLIGENCE
# Count combinations
x = [len(c) for c in countries if c]
total = triangular_number(unpaired - 1)
total += unpaired * sum(x)
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
distance = 1
visited = [source]
city = graph[source]
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())
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)
36
18CS2206 ARTIFICIAL INTELLIGENCE
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 ?
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()
for i in range(N):
board[i][col] = 1
ld[i - col + N - 1] = rd[i + col] = cl[i] = 1
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:
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
if depth == 3:
return values[nodeIndex]
if maximizingPlayer:
best = MIN
return best
else:
best = MAX
44
18CS2206 ARTIFICIAL INTELLIGENCE
return best
if __name__ == "__main__":
45
18CS2206 ARTIFICIAL INTELLIGENCE
Students Signature
(For Evaluator’s use only)
46
18CS2206 ARTIFICIAL INTELLIGENCE
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)).
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)
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
if name == "main":
print ("(alpha, beta): ", alpha, beta)
print ("Result: ", tree)
print ("Times pruned: ", 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:
MAX = 200
def findStates(position):
position[0] = 0;
position[1] = 1;
position[2] = 0;
position[3] = 1;
position[4] = 1;
position[5] = 1;
position[6] = 1;
position[7] = 0
for i in range(8,MAX+1):
position[i] = 1;
else:
position[i] = 0;
#driver function
N = 100
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
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)
55
18CS2206 ARTIFICIAL INTELLIGENCE
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
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
44
18CS2206 ARTIFICIAL INTELLIGENCE
POST LAB:
6 A)The following problems that can be solved using Constraint Satisfaction Problems (CSP):
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)
43
18CS2206 ARTIFICIAL INTELLIGENCE
44
18CS2206 ARTIFICIAL INTELLIGENCE
PRE-LAB:
1. What is the order of precedence in propositional logic in AI ?
45
18CS2206 ARTIFICIAL INTELLIGENCE
46
18CS2206 ARTIFICIAL INTELLIGENCE
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.
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
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)
51
18CS2206 ARTIFICIAL INTELLIGENCE
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
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.
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)
57
18CS2206 ARTIFICIAL INTELLIGENCE
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?
58
18CS2206 ARTIFICIAL INTELLIGENCE
Python Code:
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 = "A B C D E".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] > s[Names.B],
lambda s: abs(s[Names.E] - s[Names.C]) != 1,
lambda s: abs(s[Names.B] - s[Names.C]) != 1];
61
18CS2206 ARTIFICIAL INTELLIGENCE
Python Code:
62
18CS2206 ARTIFICIAL INTELLIGENCE
Post lab:
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
63
18CS2206 ARTIFICIAL INTELLIGENCE
64
18CS2206 ARTIFICIAL INTELLIGENCE
Students Signature
(For Evaluator’s use only)
65
18CS2206 ARTIFICIAL INTELLIGENCE
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:
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
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
z = np.c_[x_observations, v_observations]
# Initial Conditions
a = 2 # Acceleration
v = 280
t = 1 # Difference in time
# Observation Errors
error_obs_x = 25 # Uncertainty in the measurement
error_obs_v = 6
______________________________________________________________________________________
_____________________
OUTPUT :
70
18CS2206 ARTIFICIAL INTELLIGENCE
Students Signature
(For Evaluator’s use only)
71
18CS2206 ARTIFICIAL INTELLIGENCE
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
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
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)
78
18CS2206 ARTIFICIAL INTELLIGENCE
79
18CS2206 ARTIFICIAL INTELLIGENCE
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)
85
18CS2206 ARTIFICIAL INTELLIGENCE
86
18CS2206 ARTIFICIAL INTELLIGENCE
87