Ai Lab Manual
Ai Lab Manual
PROGRAM:
graph = {
‘A’ : [‘B’,’C’],
‘C’ : [‘F’],
‘D’ : [],
‘E’ : [‘F’],
‘F’ : []
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
ABCDEF
PROGRAM:
graph = {
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
print (node)
visited.add(node)
# Driver Code
PROGRAM:
V=4
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_pathweight = 0
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
# update minimum
return min_path
if __name__ == "__main__":
s=0
print(travellingSalesmanProblem(graph, s))
OUTPUT:
80/55
PROGRAM:
# objective function
def objective(x):
return x[0]**2.0
# compute targets
pyplot.plot(inputs, results)
x_optima = 0.0
pyplot.show()
# initial temperature
initial_temp = 10
pyplot.plot(iterations, temperatures)
pyplot.xlabel('Iteration')
pyplot.ylabel('Temperature')
pyplot.show()
iterations = 100
# initial temperature
initial_temp = 10
label = 'diff=%.2f' % d
# inalize plot
pyplot.xlabel('Iteration')
pyplot.ylabel('Metropolis Criterion')
pyplot.legend()
pyplot.show()
class WumpusWorldSolver:
def __init__(self, size):
self.size = size
self.grid = [[' ' for _ in range(size)] for _ in range(size)]
self.agent_location = (0, 0)
self.has_gold = False
self.has_wumpus = False
self.has_arrow = True
def print_world(self):
for row in self.grid:
print(row)
def shoot(self):
if self.has_arrow:
self.has_arrow = False
print("Arrow shot!")
def solve(self):
if self.agent_location == (0, 0):
self.move('RIGHT')
elif self.agent_location == (0, 1) and not self.has_gold:
self.grab()
elif self.agent_location == (0, 1) and self.has_gold:
self.move('LEFT')
elif self.agent_location == (0, 0):
self.move('UP')
else:
self.move('RIGHT')
# Example usage:
world = WumpusWorldSolver(size=4)
world.grid[1][1] = 'P' # Wumpus
world.grid[2][2] = 'G' # Gold
world.print_world()
world.solve()
OUTPUT:
PROGRAM:
import copy
n=3
row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]
class priorityQueue:
def __init__(self):
self.heap = []
heappush(self.heap, k)
def pop(self):
return heappop(self.heap)
def empty(self):
if not self.heap:
return True
else:
return False
class node:
self.parent = parent
self.mat = mat
self.cost = cost
self.level = level
count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1
return count
new_mat = copy.deepcopy(mat)
x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
return new_node
def printMatrix(mat):
for i in range(n):
print()
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
pq = priorityQueue()
pq.push(root)
minimum = pq.pop()
if minimum.cost == 0:
printPath(minimum)
return
for i in range(n):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]
child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)
pq.push(child)
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
empty_tile_pos = [ 1, 2 ]
123
560
784
123
506
784
123
586
704
123
586
074
PROGRAM:
class Tower:
def __init__(self):
self.terminate = 1
if disc == self.terminate:
self.printMove(source, destination)
else:
t = Tower();
A -> B
A -> C
B -> C
A -> B
C -> A
C -> B
A -> B
PROGRAM:
graph = {
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
print (node)
visited.add(node)
# Driver Code
OUTPUT:
PROGRAM:
# Creating subclass
class State_String(State):
def __init__(self, value, parent, start = 0, goal = 0 ):
super(State_String, self).__init__(value, parent, start, goal)
OUTPUT:
0)BHANU
1)BHNAU
2)BHNUA
3)HBNUA
4)HNBUA
5)NHBUA
6)NHUBA
PROGRAM:
graph = {
'5' : ['3','7'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
print (node)
visited.add(node)
# Driver Code
OUTPUT:
PROGRAM:
Starting
Done!
PROGRAM:
18
15
16
Now I will prove to you that I can count to any number you want.
10
0!
1!
2!
3!
4!
5!
6!
7!
8!
9!
10 !
.................................
.................................
.................................
.................................
.................................
.................................
PROGRAM:
import wolframalpha
app_id = '7W243X-4EHR4PWX26'
# client class
client = wolframalpha.Client(app_id)
res = client.query(question)
answer = next(res.results).text
print(answer)
Charles Babbage
PROGRAM:
# is empty, return 1
return 1
# return 0
if (m == 0):
return 0
# of both strings
# of first string
return (count(a, b, m - 1, n - 1) +
else:
return count(a, b, m - 1, n)
# Driver code
a = "GeeksforGeeks"
b = "Gks"
print(count(a, b, len(a),len(b)))
OUTPUT:
4
'Returns the count of elements in list that satisfies the given condition'
if cond:
else:
count = len(listOfElems)
return count
def main():
# List of numbers
listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101]
print('**** Use map() & sum() to count elements in a list that satisfy
certain conditions****')
# count numbers in the list which are greater than 5 but less than 20
print('Count of numbers in a list which are greater than 5 but less than 20
: ', count)
count = getCount(listOfElems)
conditions ****')
conditions ****')
0)
if __name__ == '__main__':
main()
Output:
0x79b3217c93f0>
**** Use map() & sum() to count elements in a list that satisfy certain
conditions****
** Example 1 **
** Example 1 : Explanation **
Contents of map object : [True, False, True, True, False, True, False, True,
True]
** Example 2**
**** Using sum() & Generator expression to count elements in list based on
conditions ****
Count of numbers in a list which are greater than 5 but less than 20 : None
**** Use List comprehension to count elements in list based on conditions ****
**** Use reduce() function to count elements in list based on conditions ****
PROGRAM:
class ItemValue:
def __init__(self, wt, val, ind):
self.wt = wt
self.val = val
self.ind = ind
self.cost = val
class FractionalKnapSack:
@staticmethod
def getMaxValue(wt, val, capacity):
iVal = []
for i in range(len(wt)):
iVal.append(ItemValue(wt[i], val[i], i))
# sorting items by value
iVal.sort(reverse=True)
totalValue = 0
for i in iVal:
curWt = int(i.wt)
curVal = int(i.val)
if capacity - curWt >= 0:
capacity -= curWt
# Driver Code
if __name__ == "__main__":
wt = [10, 40, 20, 30]
val = [60, 40, 100, 120]
capacity = 50
# Function call
maxValue = FractionalKnapSack.getMaxValue(wt, val, capacity)
print("Maximum value in Knapsack =", maxValue)
OUTPUT:
PROGRAM:
else:
ans.append(q[-1][1])
del q[-1]
q = sorted(q)
# Driver Code
# Given N
N=3
# Given arr[]
arr = [ 2, 1, 3 ]
# Given string
s = "001011"
# Function Call
findTheOrder(arr, s, N)
OUTPUT:
211332