0% found this document useful (0 votes)
26 views16 pages

Virtual

Project report

Uploaded by

rahulyadav957181
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
26 views16 pages

Virtual

Project report

Uploaded by

rahulyadav957181
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
INDEX Experiment Date Signature Divide and Conquer -1 Divide and Conquer -2 Implementation of Stack and Queue Hashing Techniques Applications of Stack | Binary Search 1 Tree Disjoint Set Operations | | Shortest Path Algorithm [Minimum Cost Spanning Tree : Tree Travesrsals Graph Traversal Techniques @ scanned with OKEN Scanner EXPERIMENT:1 DIVIDE AND CONQUER - { OBJECTIVE: : a. To implement Quick Sort on 1D array of Student structure (contains e, aden rll 01m), wih ky salon slo and cou the numberof en voter b. To ; See a a ID array of Student structure (contains student_name, nt_roll_no,total_marks), with key a : ? i perfor eet nt tll tl ‘ey as student_roll_no and count the number of swap performed. PROGRAM LO ‘To implement Quick Sort # This function takes last element as pivot, places 4 the pivot element a its correct position in sorted H array, and places all smaller (smaller than pivot) ¥ to eft of pivot and all greater elements to right # of pivot def partition(arr,low,high): i=(low-1) # index of smaller element pivot = arfhigh} # pivot for in range(tow , high): # If current element is smaller than the pivot if arf] < pivot: # increment index of smaller element arr{i],arr(j] = arr{j),arefi) arrfi+1 ],arr[high] = arrfhigh},arrfi+1| return (i+! ) # The main function that implements QuickSort # arr[] --> Array to be sorted, # low --> Starting index, ‘# high --> Ending index # Function to do Quick sort def quickSort(arr,low,high): if low < high: # pi is partitioning index, arr{p] is now # at right place pi = partition(arr,low.high) # Separately sort elements before # partition and after partition quickSort(arr, low, pil) quickSort(arr, pi, high) # Driver code to test above arr = {10, 7, 8, 9, 1, 5] n= len(arr) quickSort(arr,0,n-1) print ("Sorted array is:") fori in range(n): print ("%d" %arrfiJ) To implement Merge Sort i+] # Python program for implementation of MergeSont def ‘mergeSort(ar): iflen(art)>1: len(arr)//2 #Finding the mid of the array L = anr[:mial] # Dividing the array elements @ scanned with OKEN Scanner R= arr[mid:| # into 2 halves mergeSort(L) # Sorting the first half mergeSort(R) # Sorting the second half # Copy data to temp arrays L{} and R[] while i < Ten(L) and j left_sum) : le_sum = sm 4# Include elements on right of mid sm = 0; Fight_sum = -1000 for iin range(m-+ 1, h +1) sm = sm + arti] if (sm> right_sum) : right_sum = sm # Return sum of elements on left and right of mid return Jeft_sum + right_sum: # Returns sum of maxium sum subarray in aah] def maxSubArraySum(arr, |, h) # Base Case: Only one element if (1 = hy retum arr] # Find middle point m=(1+h)//2 # Return maximum of following three possible eases ¥ a) Maximum subarray sum in left hall 1b) Maximum subarray sum in right half 4c) Maximum subarray sum such that the subarray crosses the midpoint return max(maxSubArraySum(arr, |, m), ‘maxSubArraySum(arr, mL, b), maxCrossingSum(arr, I,m, h)) 4H Driver Code am=[2, 3,4, 5, 7] n= len(arr) ‘max_sum = maxSubArraySumi(arr, 0, 0-1) print("Maximum contiguous sum is ", max_sum) b) binary search. # Python Program for recursive binary search, @ scanned with OKEN Scanner # Returns index of x in ar if present, else -1 det binarySearch (arr, I # Check base case i'r >= I mid =1+(F-02 # ICelement is present at the middle itself i an rofum mid 4# If element is smaller than mid, then it # can only be present in left subarray elifars|mid] > x retum binarySearch(arr, |, mid-1, x) 4# Else the element can only be present # in right subarray else retum binarySearch(arr, mid + 1, r, x) else: # Element is not present in the array return -1 # Test array art=[2, 3, 4, 10,40] x=10 # Function call result = binarySearch(arr, 0, len(ar)-1, x) ifftesult != 1 print "Element is present at index % d” % result else: print "Element is not present in array” INPUTIOUTPUT: a) Divide and conquer algorithm 5 None b) Binary search Element is present at index 3 Faculty Sign @ scanned with OKEN Scanner EXPERIMENT: 3 IMPLEMENTATION OF STACK AND QUEUE OBJECTIVE: Implement 3-stacks of size min an array of size. with all the basic operations such as Is a Fpty().Pushi. Pop, ISFull@) where "denotes the stack number (1,2,3), Stacks are not overlapping cach other. b Design and implement Queue and its operations using Arrays. RESOURCES: Python 34 PROGRAM LOGIC: a, Stack operations class StackContainer(object): def_init_(Self, stack_count=3, size=256): self'stack_count = stack count selfstack_top = [None] * stack_count self-size=size # Create arena of doubly linked list selfarena =| {'prev': x-1, ‘next: x+1} for x in range(self-size)] self.arena{0]['prev'] = None self.arena[selfsize-l]{'next'] = None self. arena_head def _allocate( sel) new_pos = selfarena_head fre self.arena{new_pos} next = free|'next'] ifnext self-arena[next]|'prev'] = None self.arena_head = next else: self.arena_head = None return new _pos def _dump(self, stack_num): assert 0-<= stack_num root data: root right = insert(root. right, data) # retur the (unchanged) node pointer retum root # Function to find the node with maximum value # i.e. rightmost leaf node def maxValue(root): current = root #loop down to find the rightmost leaf white(current right) current = current right return current.data # Driver code if _name = main’: root-None root = insert(root,2) root = insert(root,l) root = insert(root,3) root insert(root,6) root = insert(root,5) print("Maximum value in BST is {}" format(maxValue(roo!))) INPUT/OUTPUT: 20 30 40 30. 60 70 80 Faculty Sign__ @ scanned with OKEN Scanner EXPERIMENT-7 DISJOINT SET OPERATIONS OBJECTIVE: Wnie a program to implement Make_ Set, Find_Set and Union functions for Disjoint Set ee rctre ora given undirected graph G(V.E using the linked list representation with sims implementation of Union operation RESOURCES: Python 34 PROGRAM LOGIC: INPUTIOUTPUT: graph contains cycle Faculty Sign, @ scanned with OKEN Scanner EXPERIMENTS GRAPH TRAVERSAL TECUNIQUES, OBJECTIVE: a. To print all the nodes reachable from a given starting node in a digraph using BFS method. ® b. To check whether a given graph is connected or not using DFS method. RESOURCES: Python 34 PROGRAM LOGIC: a) BFS method class Graph: def init (sel): ¥ dictionary containing keys that map to the corresponding vertex object self. vertices = {} def add_verten(self, key) ‘Add a vertex with the given Key to the graph,"*" vertex = Vertex(key) self-vertices{key] = vertex def get_verten(self, key): ‘m'Retum vertex object with the corresponding key.""" retum self vertices(key] def_contains (self, key) retum key in self. vertices def add_edge(self, ste_key, dest_key, weight=1): ‘Add edge from sre_key to dest_Key with given weight.""" self vertices[sre_key} add_neighbour(self.vertices{dest_key), weight) def does_edge enist(self, sro_key, dest_key): ‘Return True if there is an edge from sre_key to dest_Key.""" Return self-vertices[sre_key].does_it_point to(selfvertices|dest_key]) det iter (self) return iter(self vertices. values()) class Vertex: def init (self, key): self key = key self points to = {} def get_key(self): ‘Return key corresponding to this vertex object.""" retum self key def add_neighbour(self, dest, weight): ‘Make this vertex point to dest with given edge weight.""" self.points_to[dest] = weight def get_neighbours(sel0): ‘Return all vertices pointed to by this vertex.""" retum self-points_to.keys() get_weight(sel, dest: "Get weight of edge from this vertex to dest.""* return self.points_tofdest] @ scanned with OKEN Scanner def does_it_point to(self, dest swompeturn True if this vertex points 10 dest." return destin self. points. to lass Queue 7 dofinit (self): sel.items = |] def is_empty(sell) return self items = [] def enqueue(self, data): self.items. append (data) def dequeue(self) return selfitems.pop(0) def find_all_reachable_nodes( vertex): "Return set containing all vertices reachable from vertex.” visited = set() q = Queue() qenqueue(vertex) visited add(vertex) while riot q.is_emply(): current = qdequeue() for destin current.get_neighbours(); if dest not in visited: visited add(dest) qenqueue(dest) return visited : = Graph() print(‘Menu) print(add vertex ") print(‘add edye sre “dest~’) print(‘reachable “vertex ey>') print(display’) print(quit’) while True: do = input(‘What would you like to do?) split() ‘operation = do[0 if operation ‘add: suboperation = doll] if suboperation == 'vertex’ key = int(do[2)) if key notin g: g.add_yertex(key) else: print(Vertex already exists’) lif suboperation == ‘edge’: sre = int(do2)) dest = int(do[3)) if sre notin g: print("Vertex {} dows not exist format(sre)) elif dest not in g: print(Vertex {} does not exist.’ format(dest)) else’ ifnot g.does_edge_exist(src, dest): g.add_edge(sre, dest) else print(‘Edge already exists’) elif operation == "reachable: key = int(do] ]) vertex ‘g.get_vertex(key) reachable = find _all_reachable_nodes(vertex) print(‘All nodes reachable from {}:' format(key), [v.get_key() for v in reachable}) elif’ operation print('Vertices: *, en ing: print(v.get_key(), ent print() print(Edges: ') for v in 8 for dest in v.get_neighbours(): w v.get_weight(dest) print((sro=t}, dest={}, weight=(}) ‘format(y.get_key(), dest get_key(), w)) print() =f @ scanned with OKEN Scanner lifoperation break ») DFS method 4 Python program to check ifa given directed graph is strongly # connected or not from collections import defaultdict This class represents 2 directed graph using adjacency list representation class Graph: ‘def init (self.vertices): self. V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph 4# function to add an edge to graph def addEdge(selfu,v) self graph{ul append) 4#A function used by isSCO 10 perform DFS def DFSULi(selfy.visited) # Mark the current node as visited visited[y|= True ‘Recut forall the vertices adjacent to this vertex fori in self-graph{v}: if Visited|i]—False: self DFSUtil(i,visited) # Function that retums reverse (or transpose) of this graph def getTranspose(elf) Graph(sel.V) # Recur for all the vertices adjacent to this vertex for iin self graph: for in self. graphfi} g.addEdge(.i) retum g # The main function that retums true if graph is strongly connected def isSCi(Self): # Step 1: Mark all the vertices as not visited (For first DFS) visited =[False]*(self V) # Step 2: Do DFS traversal starting from first vertex. self DFSUtil(0,visited) # AEDES traversal doesnt visit all vertices, then retum false if any(i = False fori in visited) return False # Step 3: Create a reversed graph gr = self getTranspose() # Step 4: Mark all the vertices as not visited (For second DFS) visited =[False]*(selfV) # Step 5: Do DFS for reversed graph starting from first vertex. # Staring Vertex must be same starting point of first DES gr-DFSUtI(0,sisited) # Ifall vertices are not visited in second DFS, then False fori in visited): return False retum True # Create a graph given in the above diagram gl = Graph(5) g1.addEdge(0, 1) gl addEdge(|, 2) gladdEdge(2, 3) gl.addEdge(3, 0) gl.addEdge(2, 4) g.addEdge(4, 2) print "Yes" if gl isSCO) else "No" 22 = Graph(4) g2.addEdge(0, g2.addEdge(!, 2) g2.addEdge(2, 3) print "Yes" if'g2.isSCO else "No" INPUT/OUTPUT: BFS Case 1: Menu add vertex add edge display quit DFS Case 1: Menu add vertex add edge dfs display quit Faculty Sign, @ scanned with OKEN Scanner EXPERIMENT-9 / dog HORTEST PATHS ALGORETHM om From a given vertex in a weighted connected graph, find shores paths to ather v using Dijkstea’s algorithm. , _ RESOURCES: Python 3.4 PROGRAM LOGIC: class Graph: do init sel: # dictionary containing keys that map to the vertex ae tA a ee P to the corresponding vertex object self-vertices = {} def "Add a vertex with the given key to the graph.""" vertex = Vertex(key) self-vertices[key] = vertex def get_vertex(self, key) "Return vertex object with the corresponding key.""" retum self.vertices[key] def_contains (self, key): return key in self-vertices defadd_edge(self, ste_key, dest_key, weight=1) "Add edge from stc_key to dest_key with given weight.""" self.-vertices[sre,_key/.add_neighbour(self vertices{dest_key], weight) def does_edge_exisi(self sro_key, dest_key) 'Retum True if there is an edge from sre key to dest key.""" Retum self-vertices|src_key].does_it_point_to(self.vertices|dest_key]) def_iter (self); retum iter(self. vertices. values() class Vert def init (self, key): self key = key self points t= {} def get_key(selt): ‘"Retum key corresponding to this vertex object" retum self key def add_neighbour(self; dest, weight): ‘w"Make this vertex point to dest with given edge weight.""" self points_tofdest] def get_neighbours(self): ‘~"Retum all vertices pointed to by this vertes.""" return self-points_to.keys() def get_weight(self, dest): "miGat weight of edge from this vertex to dest.""" retum self.points_to[dest] def does_it_point_to(self, dest): “Return True if this vertex points to dest.""" return dest in self-points_to def dijkstra(g, source) ““Retum distance where distance{v] is min distance from source tov. This will return a dictionary distance. g is a Graph object. source isa Vertex object in g,""" unvsited = set(g) distance = diet fromkeys(g, float( inf) distancefsource] = 0 while unvisited = set0: # find vertex with minimum distance closest = min(unvisited, key=lambda v: distance[]) +# mark as visited unvisited remove(closest) # update distances for neighbour in closest get_neighbours(: it neighbour in unvisited: new_distance = distance[closest] + closest get_weight(neighbour) if distance{neighbour] > new. distance: distance[neighbour] =new distance retum distance @ scanned with OKEN Scanner

You might also like