Practical 1A) Write a program to implement depth first search algorithm.
def dfs(graph, start, visited=None):
for next in graph[start] - visited:
dfs(graph, next, visited)
graph = {'0': set(['1', '2']),
'1': set(['0', '3', '4']),
Practical 1B) Write a program to implement breadth first search algorithm.
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
while queue: # Creating loop to visit each node
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
Practical 2A) Write a program to simulate 4-Queen / N-Queen problem.
def printSolution(board):
print (board[i][j],end=' ')
def isSafe(board, row, col):
# Check this row on left side
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
# Check lower diagonal on left side
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
def solveNQUtil(board, col):
# base case: If all queens are placed
if isSafe(board, i, col):
if solveNQUtil(board, col + 1) == True:
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
Practical 2B) Write a program to solve tower of Hanoi problem.
def TowerOfHanoi(n , source, destination, auxiliary):
print ("Move disk 1 from source",source,"to destination",destination)
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
print("Practical 3a - Alpha Beta Search")
print("\nDharmik Pansuriya 53003200001")
# Initial values of Alpha and Beta
# Returns optimal value for current player
def minmax(depth, nodeIndex, maximizingPlayer, values, alpha, beta):
# Terminating condition. i.e # leaf node is reached
# Recur for left and right children
val = minmax(depth + 1, nodeIndex * 2 + i,
False, values, alpha, beta)
val = minmax(depth + 1, nodeIndex * 2 +
i, True, values, alpha, beta)
if __name__ == "__main__":
values = [10, 11, 9, 12, 14, 15, 13, 14, 5, 2, 4,
1, 3, 22, 20, 21] # [2, 3, 5, 9, 0, 1, 7, 5]
print("The optimal value is :", minmax(0, 0, True, values, MIN, MAX))
PRACTICAL : 3A ALPHA BETA SEARCH
print("Practical 3a - Alpha Beta Search")
print("\nDharmik Pansuriya 53003200001")
# Initial values of Alpha and Beta
# Returns optimal value for current player
def minmax(depth, nodeIndex, maximizingPlayer, values, alpha, beta):
# Terminating condition. i.e # leaf node is reached
# Recur for left and right children
val = minmax(depth + 1, nodeIndex * 2 + i,
False, values, alpha, beta)
val = minmax(depth + 1, nodeIndex * 2 +
i, True, values, alpha, beta)
if __name__ == "__main__":
values = [10, 11, 9, 12, 14, 15, 13, 14, 5, 2, 4,
1, 3, 22, 20, 21] # [2, 3, 5, 9, 0, 1, 7, 5]
print("The optimal value is :", minmax(0, 0, True, values, MIN, MAX))
PRACTICAL:3B HILL CLIMBING:
print("Practical 3b - Hill Climbing")
print("Dharmik Pansuriya - 53003200001\n")
def distance(x1, y1, x2, y2):
dist = math.pow(x2-x1, 2) + math.pow(y2-y1, 2)
def sumOfDistances(x1, y1, px1, py1, px2, py2, px3, py3, px4, py4):
d1 = distance(x1, y1, px1, py1)
d2 = distance(x1, y1, px2, py2)
d3 = distance(x1, y1, px3, py3)
d4 = distance(x1, y1, px4, py4)
def newDistance(x1, y1, point1, point2, point3, point4):
d1temp = sumOfDistances(x1, y1, point1[0],point1[1], point2[0],point2[1],point3[0],point3[1],
minDistance = sumOfDistances(startingPoint[0], startingPoint[1], point1[0],point1[1],
point2[0],point2[1],point3[0],point3[1], point4[0],point4[1] )
def newPoints(minimum, d1, d2, d3, d4):
d1 = newDistance(startingPoint[0]+increment, startingPoint[1], point1, point2, point3, point4)
d2 = newDistance(startingPoint[0]-increment, startingPoint[1], point1, point2, point3, point4)
d3 = newDistance(startingPoint[0], startingPoint[1]+increment, point1, point2, point3, point4)
d4 = newDistance(startingPoint[0], startingPoint[1]-increment, point1, point2, point3, point4)
print (i,'', round(startingPoint[0], 2), round(startingPoint[1], 2))
minimum = min(d1[2], d2[2], d3[2], d4[2])
if minimum < minDistance:
startingPoint = newPoints(minimum, d1, d2, d3, d4)
#print I,’ ‘, round(startingPoint[0], 2), round(startingPoint[1], 2)
print("Practical 4a - A* Algorithm")
print("Dharmik Pansuriya - 53003200001\n")
def aStarAlgo(start_node, stop_node):
open_set = set(start_node)
g = {} # store distance from starting node
parents = {} # parents contains an adjacency map of all nodes
# distance of starting node from itself is zero
parents[start_node] = start_node
# node with lowest f() is found
if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):
if n == stop_node or Graph_nodes[n] == None:
for (m, weight) in get_neighbors(n):
# nodes 'm' not in first and last set are added to first
if m not in open_set and m not in closed_set:
# change parent of m to n
# if m in closed set,remove and add to open
print('Path does not exist!')
# if the current node is the stop_node then we begin reconstructin the path from it to the start_node
print('Path found: {}'.format(path))
# remove n from the open_list, and add it to closed_list because all of his neighbors were inspected
print('Path does not exist!')
# define fuction to return neighbor and its distance from the passed node
'A': [('B', 6), ('F', 3)],
'B': [('A', 6), ('C', 3), ('D', 2)],
'C': [('B', 3), ('D', 1), ('E', 5)],
'D': [('B', 2), ('C', 1), ('E', 8)],
'E': [('C', 5), ('D', 8), ('I', 5), ('J', 5)],
'F': [('A', 3), ('G', 1), ('H', 7)],
'G': [('F', 1), ('I', 3)],
'H': [('F', 7), ('I', 2)],
'I': [('E', 5), ('G', 3), ('H', 2), ('J', 3)],
print("Practical 4b - AO* Algorithm")
print("Dharmik Pansuriya - 53003200001\n")
# instantiate graph object with graph topology, heuristic values, start node
def __init__(self, graph, heuristicNodeList, startNode):
self.H = heuristicNodeList
def applyAOStar(self): # starts a recursive AO* algorithm
self.aoStar(self.start, False)
def getNeighbors(self, v): # gets the Neighbors of a given node
return self.graph.get(v, '')
def getStatus(self, v): # return the status of a given node
return self.status.get(v, 0)
def setStatus(self, v, val): # set the status of a given node
def getHeuristicNodeValue(self, n):
# always return the heuristic value of a given node
def setHeuristicNodeValue(self, n, value):
self.H[n] = value # set the revised heuristic value of a given node
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE:", self.start)
print("------------------------------------------------------------")
print(self.solutionGraph)
print("------------------------------------------------------------")
# Computes the Minimum Cost of child nodes of a given node v
def computeMinimumCostChildNodes(self, v):
costToChildNodeListDict = {}
costToChildNodeListDict[minimumCost] = []
# iterate over all the set of child node/s
for nodeInfoTupleList in self.getNeighbors(v):
for c, weight in nodeInfoTupleList:
cost = cost+self.getHeuristicNodeValue(c)+weight
if flag == True: # initialize Minimum Cost with the cost of first set of child node/s
# set the Minimum Cost child node/s
costToChildNodeListDict[minimumCost] = nodeList
else: # checking the Minimum Cost nodes with the current Minimum Cost
# set the Minimum Cost child node/s
costToChildNodeListDict[minimumCost] = nodeList
# return Minimum Cost and Minimum Cost child node/s
return minimumCost, costToChildNodeListDict[minimumCost]
def aoStar(self, v, backTracking): # AO* algorithm for a start node and backTracking status flag
print("HEURISTIC VALUES :", self.H)
print("SOLUTION GRAPH :", self.solutionGraph)
print("PROCESSING NODE :", v)
print("-----------------------------------------------------------------------------------------")
if self.getStatus(v) >= 0: # if status node v >= 0, compute Minimum Cost nodes of v
minimumCost, childNodeList = self.computeMinimumCostChildNodes(v)
print(minimumCost, childNodeList)
self.setHeuristicNodeValue(v, minimumCost)
self.setStatus(v, len(childNodeList))
solved = True # check the Minimum Cost nodes of v are solved
for childNode in childNodeList:
self.parent[childNode] = v
if self.getStatus(childNode) != -1:
# if the Minimum Cost nodes of v are solved, set the current node status as solved(-1)
# update the solution graph with the solved nodes which may be a part of solution
self.solutionGraph[v] = childNodeList
self.aoStar(self.parent[v], True)
if backTracking == False: # check the current call is not for backtracking
for childNode in childNodeList: # for each Minimum Cost child node
# set the status of child node to 0(needs exploration)
self.setStatus(childNode, 0)
self.aoStar(childNode, False)
h1 = {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2,
'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
'A': [[('B', 1), ('C', 1)], [('D', 1)]],
'B': [[('G', 1)], [('H', 1)]],
'D': [[('E', 1), ('F', 1)]],
G1 = Graph(graph1, h1, 'A')
print("Practical 5a - WaterJug")
print("Dharmik Pansuriya - 53003200001\n")
def __init__(self,am,bm,a,b,g):
if (self.a == 0 or self.b ==self.b_max):
if (self.a == self.goal or self.b == self.goal):
elif (self.a > 0 and self.b != self.b_max):
elif (self.a > 0 and self.b == self.b_max):
waterjug=Waterjug(4,3,0,0,2);
Practical 5B) Tic Tac Tow using Min Max Algo
print("Practical 5b - Tic Tac Toe")
print("Dharmik Pansuriya - 53003200001\n")
print(board[1]+'|'+board[2]+'|'+board[3])
print(board[4] + '|' + board[5] + '|' + board[6])
print(board[7] + '|' + board[8] + '|' + board[9])
def spaceIsFree(position):
if board[position] == ' ':
def insertLetter(letter, position):
if spaceIsFree(position):
print("Can insert there!")
position = int(input("Please enter new position: "))
insertLetter(letter, position)
if (board[1] == board[2] and board[1] == board[3] and board[1] != ' '):
elif (board[4] == board[5] and board[4] == board[6] and board[4] != ' '):
elif (board[7] == board[8] and board[7] == board[9] and board[7] != ' '):
elif (board[1] == board[4] and board[1] == board[7] and board[1] != ' '):
elif (board[2] == board[5] and board[2] == board[8] and board[2] != ' '):
elif (board[3] == board[6] and board[3] == board[9] and board[3] != ' '):
elif (board[1] == board[5] and board[1] == board[9] and board[1] != ' '):
elif (board[7] == board[5] and board[7] == board[3] and board[7] != ' '):
def checkWhichMarkWon(mark):
if (board[1] == board[2] and board[1] == board[3] and board[1] == mark):
elif (board[4] == board[5] and board[4] == board[6] and board[4] == mark):
elif (board[7] == board[8] and board[7] == board[9] and board[7] == mark):
elif (board[1] == board[4] and board[1] == board[7] and board[1] == mark):
elif (board[2] == board[5] and board[2] == board[8] and board[2] == mark):
elif (board[3] == board[6] and board[3] == board[9] and board[3] == mark):
elif (board[1] == board[5] and board[1] == board[9] and board[1] == mark):
elif (board[7] == board[5] and board[7] == board[3] and board[7] == mark):
position = int(input("Enter position for O: "))
insertLetter(player, position)
score = minimax(board, 0, False)
insertLetter(bot, bestMove)
def minimax(board, depth, isMaximizing):
if (checkWhichMarkWon(bot)):
elif (checkWhichMarkWon(player)):
score = minimax(board, depth + 1, False)
score = minimax(board, depth + 1, True)
board = {1: ' ', 2: ' ', 3: ' ',
print("Computer goes first! Good Luck.")
print("position are as follows:")
Practical 6A) Shuffle Deck Of Card
print("Practical 6 - Card Shuffle")
print("Dharmik Pansuriya - 53003200001\n")
deck=list(itertools.product(range(1,14),['spade','Heart','Diamond','Club']))
print(deck[i][0],"of",deck[i][1])
Practical 7a:ASSOCIATIVE LAW
lbscitadmission(X):-((student(X),hscstudent(X)),sscstudent(X)).
rbscitadmission(X):-(student(X),(hscstudent(X),sscstudent(X))).
Practical 7b:DISTRIBUTIVE LAW
lmorefamous(X):-male(X),(artist(X),sculptor(X)).
rmorefamous(X):-((male(X),artist(X));(male(X),sculptor(X))).
Practical 8a:DERIVE THE PREDICATE
cricketer(batsman,cricketer).
profile(X,Y):-batsman(X,Z),cricketer(Z,Y).
Practical 8b:ANSWER FROM PREDICATE
female(X):-mother_of(X,Y).
son_of(X,Y):-father_of(Y,X),male(X).
son_of(X,Y):-mother_of(Y,X),male(X).
daughter_of(X,Y):-father_of(Y,X),female(X).
daughter_of(X,Y):-mother_of(Y,X),female(X).