DSAI Lab Programs
DSAI Lab Programs
and returns the dot product of a and b. That is, it returns an array c of length n such that
c[i]=a[i]·b[i],
for i = 0,...,n-1.
def dot_product(v1,v2):
print(dot_product([1,2,3],[3,5,7]))
O/P:
34
2) #Write a python program to implement Tower of Hanoi Puzzle.
if n==1:
return
-----------------------------------------------------------------------
if(disks == 1):
return
-----------------------------------------------------------------------
-----------------------------------------------------------------------
if disks == 1:
return
-----------------------------------------------------------------------
O/P:
class DynamicArray(object):
def __init__(self):
self.A = self.make_array(self.capacity)
def __len__(self):
return self.n
if self.n == self.capacity:
self._resize(2 * self.capacity)
self.n += 1
def insertAt(self,item,index):
if index<0 or index>self.n:
return
if self.n==self.capacity:
self._resize(2*self.capacity)
for i in range(self.n-1,index-1,-1):
self.A[i+1]=self.A[i]
self.A[index]=item
self.n+=1
def delete(self):
if self.n==0:
return
self.A[self.n-1]=0
self.n-=1
def removeAt(self,index):
if self.n==0:
return
if index<0 or index>=self.n:
if index==self.n-1:
self.A[index]=0
self.n-=1
return
for i in range(index,self.n-1):
self.A[i]=self.A[i+1]
self.A[self.n-1]=0
self.n-=1
B[k] = self.A[k]
# Instantiate
arr = DynamicArray()
arr.append(1)
len(arr)
arr.insertAt(12,0)
len(arr)
for i in range(len(arr)):
print(arr[i],end="")
O/P:
121
4) #Write a python program to determine if a strings has more vowels then consonants.
vowels = 0
consonants = 0
str1.lower()
for i in str1:
vowels = vowels + 1
else:
consonants = consonants + 1
--------------------------------------------------------------------------------
O/P:
5) #Write a python program to implement parentheses matching and HTML tags using
array based stack.
open_list=["[","{","(","<"]
close_list=["]","}",")",">"]
def check(mystr):
stack = []
for i in mystr:
if i in open_list:
stack.append(i)
elif i in close_list:
pos=close_list.index(i)
stack.pop()
else:
if len(stack)==0:
else:
string="{<[]{()}>}"
print(string, "_",check(string))
string="[{<}{}[>]]"
print(string, "_",check(string))
print(string, "_",check(string))
--------------------------------
O/P:
value=list1[i]
j=i-1
list1[j+1]=list1[j]
j-=1
list1[j+1]=value
return list1
list1 = [10,5,13,8,2]
O/P:
7) #Write a python program to implement Tic- Toc- Toe game using two dimensional
arrays.
def main():
introduction = intro()
board = create_grid()
pretty = printPretty(board)
full = isFull(board, symbol_1, symbol_2) # The function that starts the game is also in here.
def intro():
# This function introduces the rules of the game Tic Tac Toe
print("\n")
"marking the spaces in a 3*3 grid. The player who succeeds in placing "
print("\n")
print("\n")
def create_grid():
return board
def sym():
if symbol_1 == "X":
symbol_2 = "O"
else:
symbol_2 = "X"
print("\n")
if count % 2 == 0:
player = symbol_1
elif count % 2 == 1:
player = symbol_2
"[upper row: enter 0, middle row: enter 1, bottom row: enter 2]:"))
"[left column: enter 0, middle column: enter 1, right column enter 2]"))
while (row > 2 or row < 0) or (column > 2 or column < 0):
outOfBoard(row, column)
"[left column: enter 0, middle column: enter 1, right column enter 2]"))
"[left column: enter 0, middle column: enter 1, right column enter 2]"))
if player == symbol_1:
board[row][column] = symbol_1
else:
board[row][column] = symbol_2
return (board)
count = 1
winner = True
pretty = printPretty(board)
if count == 9:
if winner == True:
count += 1
if winner == False:
print("Game over.")
# This function tells the players that their selection is out of range
def printPretty(board):
rows = len(board)
cols = len(board)
print("---+---+---")
for r in range(rows):
print("---+---+---")
return board
winner = True
winner = False
winner = False
winner = False
winner = False
winner = False
winner = False
winner = False
winner = False
return winner
print("\n")
else:
# Call Main
main()
----------------------------------------------------------------------------
O/P:
Rules: Player 1 and player 2, represented by X and O, take turns marking the spaces in a 3*3 grid. The player who
succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins.
---+---+---
| |
---+---+---
| |
---+---+---
| |
---+---+---
Pick a row:[upper row: enter 0, middle row: enter 1, bottom row: enter 2]:1
Pick a column:[left column: enter 0, middle column: enter 1, right column enter 2]2
---+---+---
| |
---+---+---
| |O
---+---+---
| |
---+---+---
Pick a row:[upper row: enter 0, middle row: enter 1, bottom row: enter 2]:
8) #write a python program to implement stack abstract data type using Python List
stack = []
def top(stack):
if stack!=[]:
else:
print("stack is empty")
def size(stack):
def empty(stack):
if stack==[]:
print("True")
else:
print("False")
#Append function is used to push element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
size(stack)
print(stack)
top(stack)
print(stack)
empty(stack)
print(stack)
empty(stack)
O/P:
cis popped
['a', 'b']
False
bis popped
ais popped
[]
True
9) #write a python program to implement Round robin scheduler using circular linked list
class RoundRobin:
process_data = []
for i in range(no_of_processes):
temporary = []
process_data.append(temporary)
start_time = []
exit_time = []
executed_process = []
ready_queue = []
s_time = 0
process_data.sort(key=lambda x: x[1])
while 1:
normal_queue = []
temp = []
for i in range(len(process_data)):
present = 0
if len(ready_queue) != 0:
for k in range(len(ready_queue)):
if process_data[i][0] == ready_queue[k][0]:
present = 1
if present == 0:
ready_queue.append(temp)
temp = []
for k in range(len(ready_queue)):
elif process_data[i][3] == 0:
normal_queue.append(temp)
temp = []
break
if len(ready_queue) != 0:
start_time.append(s_time)
e_time = s_time
exit_time.append(e_time)
executed_process.append(ready_queue[0][0])
for j in range(len(process_data)):
if process_data[j][0] == ready_queue[0][0]:
break
ready_queue.pop(0)
start_time.append(s_time)
e_time = s_time
exit_time.append(e_time)
executed_process.append(ready_queue[0][0])
for j in range(len(process_data)):
if process_data[j][0] == ready_queue[0][0]:
break
process_data[j][2] = 0
process_data[j][3] = 1
process_data[j].append(e_time)
ready_queue.pop(0)
elif len(ready_queue) == 0:
s_time = normal_queue[0][1]
start_time.append(s_time)
e_time = s_time
exit_time.append(e_time)
executed_process.append(normal_queue[0][0])
for j in range(len(process_data)):
if process_data[j][0] == normal_queue[0][0]:
break
start_time.append(s_time)
e_time = s_time
exit_time.append(e_time)
executed_process.append(normal_queue[0][0])
for j in range(len(process_data)):
if process_data[j][0] == normal_queue[0][0]:
break
process_data[j][2] = 0
process_data[j][3] = 1
process_data[j].append(e_time)
total_turnaround_time = 0
for i in range(len(process_data)):
process_data[i].append(turnaround_time)
return average_turnaround_time
total_waiting_time = 0
for i in range(len(process_data)):
process_data[i].append(waiting_time)
return average_waiting_time
process_data.sort(key=lambda x: x[0])
for i in range(len(process_data)):
for j in range(len(process_data[i])):
print()
if __name__ == "__main__":
rr = RoundRobin()
rr.processData(no_of_processes)
O/P:
34 1 0 1
3 6 5
2
45 2 0 1
34 38 36
2
Sequence of Processes: [34, 45, 34, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45]
10) Write a python program to implement Binary Tree Traversal Techniques for Tic-Tac-
Toe game playing using breadth-first traversal order.
import numpy as np
import random
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))
def possibilities(board):
l = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)
selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)
win = True
y=0
for x in range(len(board)):
if board[x, x] != player:
win = False
if win:
return win
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win
# a winner or a tie
def evaluate(board):
winner = 0
if (row_win(board, player) or
col_win(board, player) or
diag_win(board, player)):
winner = player
winner = -1
return winner
def play_game():
print(board)
sleep(2)
while winner == 0:
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
# Driver Code
O/P:
[[0 0 0]
[0 0 0]
[0 0 0]]
[[1 0 0]
[0 0 0]
[0 0 0]]
[[1 0 0]
[0 0 2]
[0 0 0]]
[[1 0 0]
[0 0 2]
[1 0 0]]
[[1 0 2]
[0 0 2]
[1 0 0]]
[[1 0 2]
[0 0 2]
[1 0 1]]
[[1 0 2]
[2 0 2]
[1 0 1]]
Board after 7 move
[[1 0 2]
[2 0 2]
[1 1 1]]
Winner is: 1
11) Write a python program to implement Euler Tours traversal to find order of cities in a
traveling sales man problem.
# update minimum
min_path = min(min_path, current_pathweight)
return min_path
# Driver Code
if __name__ == "__main__":
O/P:
80
12) Write a python program to evaluate an arithmetic expression using expression tree.
class node:
def __init__(self, value):
self.left = None
self.data = value
self.right = None
def evaluateExpressionTree(root):
# empty tree
if root is None:
return 0
# leaf node
if root.left is None and root.right is None:
return int(root.data)
else:
return left_sum // right_sum
root = None
O/P:
60
110
13) Write a python program to implement KMP (Knuth-Morris-Pratt) Algorithm to match
the given pattern of characters.
M=len(pat)
N=len(txt)
lps=[0]*M
computeLPSArray(pat, M, lps)
while i < N:
if pat[j]==txt[i]:
i += 1
j += 1
if j == M:
j=lps[j-1]
if j!=0:
j=lps[j-1]
else:
i += 1
i=1
while i < M:
if pat[i] ==pat[len]:
len += 1
lps[i]=len
i += 1
else:
if len !=0:
len=lps[len-1]
else:
lps[i]=0
i += 1
txt="ABABDABACDABABCABAB"
pat="ABABCABA"
KMPSearch(pat, txt)
16) DFS
def dfs(graph,start,visited=None):
if visited is None:
visited=set()
visited.add(start)
print(start)
dfs(graph,next,visited)
return visited
graph = {'0':set(['1','2','3']),'1':set(['2','0']),'2':set(['0','4']),'3':set(['0']),'4':set(['2'])}
dfs(graph,'0')
O/P:
a) A* Search
open_set = set(start_node)
closed_set = set()
g[start_node] = 0
parents[start_node] = start_node
n = None
for v in open_set:
n=v
pass
else:
#nodes 'm' not in first and last set are added to first
open_set.add(m)
parents[m] = n
else:
#update g(m)
#change parent of m to n
parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
return None
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
return path
# remove n from the open_list, and add it to closed_list
open_set.remove(n)
closed_set.add(n)
return None
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 99,
'D': 1,
'E': 7,
'G': 0,
return H_dist[n]
Graph_nodes = {
'A': [('B', 2), ('E', 3)],
'C': None,
aStarAlgo('A', 'G')
O/P:
b) Best-first search
v = 14
visited = [False] * n
pq = PriorityQueue()
pq.put((0,actual_src))
visited[actual_src] = True
u = pq.get()[1]
print(u,end=" ")
if u == target:
break
for v, c in graph[u]:
if visited[v] == False:
visited[v] = True
pq.put((c,v))
print()
graph[y].append((x,cost))
addedge(0,1,3)
addedge(0,2,6)
addedge(0,3,5)
addedge(1,4,9)
addedge(1,5,8)
addedge(2,6,12)
addedge(2,7,14)
addedge(3,8,7)
addedge(8,9,5)
addedge(8,10,6)
addedge(9,11,1)
addedge(9,12,10)
addedge(9,13,2)
source = 0
target = 9
best_first_search(source, target, v)
O/P:
def generateSquare(n):
# slots set to 0
magicSquare = [[0 for x in range(n)]
for y in range(n)]
# initialize position of 1
i=n/2
j=n-1
num = 1
j=n-2
i=0
else:
if j == n:
j=0
if i < 0:
i=n-1
j=j-2
i=i+1
continue
else:
magicSquare[int(i)][int(j)] = num
num = num + 1
j=j+1
i = i - 1 # 1st condition
# To display output
# in matrix form
if j == n - 1:
print()
# Driver Code
generateSquare(n)
O/P:
2 7 6
9 5 1
4 3 8
def dfs(graph,start,visited=None):
if visited is None:
visited=set()
visited.add(start)
print(start)
dfs(graph,next,visited)
return visited
graph = {'0':set(['1','2','3']),'1':set(['2','0']),'2':set(['0','4']),'3':set(['0']),'4':set(['2'])}
dfs(graph,'0')
O/P:
class Graph:
def __init__(self, graph, heuristicNodeList, startNode): #instantiate graph object with graph topology, heuristic
values, start node
self.graph = graph
self.H=heuristicNodeList
self.start=startNode
self.parent={}
self.status={}
self.solutionGraph={}
self.aoStar(self.start, False)
return self.graph.get(v,'')
return self.status.get(v,0)
self.status[v]=val
def printSolution(self):
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE:",self.start)
print("------------------------------------------------------------")
print(self.solutionGraph)
print("------------------------------------------------------------")
def computeMinimumCostChildNodes(self, v): # Computes the Minimum Cost of child nodes of a given node v
minimumCost=0
costToChildNodeListDict={}
costToChildNodeListDict[minimumCost]=[]
flag=True
for nodeInfoTupleList in self.getNeighbors(v): # iterate over all the set of child node/s
cost=0
nodeList=[]
cost=cost+self.getHeuristicNodeValue(c)+weight
nodeList.append(c)
if flag==True: # initialize Minimum Cost with the cost of first set of child node/s
minimumCost=cost
flag=False
else: # checking the Minimum Cost nodes with the current Minimum Cost
if minimumCost>cost:
minimumCost=cost
return minimumCost, costToChildNodeListDict[minimumCost] # return Minimum Cost and Minimum Cost child
node/s
def aoStar(self, v, backTracking): # AO* algorithm for a start node and backTracking status flag
print("-----------------------------------------------------------------------------------------")
print(minimumCost, childNodeList)
self.setHeuristicNodeValue(v, minimumCost)
self.setStatus(v,len(childNodeList))
self.parent[childNode]=v
if self.getStatus(childNode)!=-1:
if solved==True: # if the Minimum Cost nodes of v are solved, set the current node status as solved(-1)
self.setStatus(v,-1)
self.solutionGraph[v]=childNodeList # update the solution graph with the solved nodes which may be a
part of solution
if v!=self.start: # check the current node is the start node for backtracking the current node value
self.aoStar(self.parent[v], True) # backtracking the current node value with backtracking status set to
true
self.aoStar(childNode, False) # Minimum Cost child node is further explored with backtracking status
as false
h1 = {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
graph1 = {
G1.applyAOStar()
G1.printSolution()
O/P:
Graph - 1
HEURISTIC VALUES : {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
-----------------------------------------------------------------------------------------
10 ['B', 'C']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : B
-----------------------------------------------------------------------------------------
6 ['G']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
-----------------------------------------------------------------------------------------
10 ['B', 'C']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : G
-----------------------------------------------------------------------------------------
8 ['I']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : B
-----------------------------------------------------------------------------------------
8 ['H']
HEURISTIC VALUES : {'A': 10, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
-----------------------------------------------------------------------------------------
12 ['B', 'C']
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : I
-----------------------------------------------------------------------------------------
0 []
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : G
-----------------------------------------------------------------------------------------
1 ['I']
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
-----------------------------------------------------------------------------------------
2 ['G']
HEURISTIC VALUES : {'A': 12, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : A
-----------------------------------------------------------------------------------------
6 ['B', 'C']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : C
-----------------------------------------------------------------------------------------
2 ['J']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : A
-----------------------------------------------------------------------------------------
6 ['B', 'C']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : J
-----------------------------------------------------------------------------------------
0 []
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 0}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': []}
PROCESSING NODE : C
-----------------------------------------------------------------------------------------
1 ['J']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 1, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 0}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J']}
PROCESSING NODE : A
-----------------------------------------------------------------------------------------
5 ['B', 'C']
FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE: A
------------------------------------------------------------
{'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J'], 'A': ['B', 'C']}
import random
def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []
for i in range(len(tsp)):
solution.append(randomCity)
cities.remove(randomCity)
return solution
routeLength = 0
for i in range(len(solution)):
return routeLength
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours
bestNeighbour = neighbours[0]
bestRouteLength = currentRouteLength
bestNeighbour = neighbour
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
neighbours = getNeighbours(currentSolution)
currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
neighbours = getNeighbours(currentSolution)
def main():
tsp = [
print(hillClimbing(tsp))
if __name__ == "__main__":
main()
O/P:
adj[v].append(w)
adj[w].append(v)
return adj
result[0] = 0;
available = [False] * V
for i in adj[u]:
if (result[i] != -1):
available[result[i]] = True
cr = 0
while cr < V:
if (available[cr] == False):
break
cr += 1
result[u] = cr
for i in adj[u]:
if (result[i] != -1):
available[result[i]] = False
for u in range(V):
# Driver Code
if __name__ == '__main__':
g1 = addEdge(g1, 0, 1)
g1 = addEdge(g1, 0, 2)
g1 = addEdge(g1, 1, 2)
g1 = addEdge(g1, 1, 3)
g1 = addEdge(g1, 2, 3)
g1 = addEdge(g1, 3, 4)
greedyColoring(g1, 5)
g2 = addEdge(g2, 0, 1)
g2 = addEdge(g2, 0, 2)
g2 = addEdge(g2, 1, 2)
g2 = addEdge(g2, 1, 4)
g2 = addEdge(g2, 2, 4)
g2 = addEdge(g2, 4, 3)
greedyColoring(g2, 5)
Coloring of graph 1
Coloring of graph 2