Package: pyalgs
pyalgsPackage pyalgs implements algorithms in the “Algorithms” book (http://algs4.cs.princeton.edu/home/) and Robert Sedgwick’s Algorithms course using Python (Part I and Part II)More details are provided in thedocsfor implementation, complexities and further info.Install pyalgsRun the following command to install pyalgs using pip$pipinstallpyalgsFeatures:Data StructureStackLinked ListArrayQueueLinked ListArrayBagHashSetHashMapSeparate ChainingLinear ProbingBinary Search TreeRed Black TreePriority QueueMinPQMaxPQIndexMinPQGraphSimple graphEdge weighted graphDirected graph (digraph)Directed edge weight graphSearch Tries (Symbol table with string-based keys)R-way search triesTernary search triesAlgorithmsSortingSelection SortInsertion SortShell SortMerge SortQuick Sort3-Ways Quick SortHeap SortSelectionBinary SearchShufflingKnuthUnion FindQuick FindWeighted Quick Union with path compressionGraph AlgorithmsSearchDepth First SearchBreadth First SearchConnectivityConnected ComponentsStrongly Connected ComponentsTopological SortingDepth First Reverse Post OrderDirected Cycle DetectionMinimum Spanning TreeKruskalPrim (Lazy)Prim (Eager)Shortest PathDijkstraTopological Sort (for directed acyclic graph, namely dag)Bellman-Ford (for graph with negative weight as well)MaxFlow MinCutFord-FulkersonStringsLongest Repeated SubstringString SortingLSD (Least Significant Digit first radix sorting)MSD (Most Significant Digit first radix sorting)3-Ways String Quick SortString SearchBrute forceRabin KarpBoyer MooreKnuth Morris PrattUsage:Data StructureStackfrompyalgs.data_structures.commons.stackimportStackstack=Stack.create()stack.push(10)stack.push(1)print[iforiinstack.iterate()]printstack.is_empty()printstack.size()popped_item=stack.pop()printpopped_itemQueuefrompyalgs.data_structures.commons.queueimportQueuequeue=Queue.create()queue.enqueue(10)queue.enqueue(20)queue.enqueue(30)print[iforiinqueue.iterate()]printqueue.size()printqueue.is_empty()deleted_item=queue.dequeue())printdeleted_itemBagfrompyalgs.data_structures.commons.bagimportBagbag=Bag.create()bag.add(10)bag.add(20)bag.add(30)print[iforiinbag.iterate()]printbag.size()printbag.is_empty()Minimum Priority Queuefrompyalgs.data_structures.commons.priority_queueimportMinPQpq=MinPQ.create()pq.enqueue(10)pq.enqueue(5)pq.enqueue(12)pq.enqueue(14)pq.enqueue(2)printpq.is_empty()printpq.size()print[iforiinpq.iterate()]deleted=pq.del_min()print(deleted)Maximum Priority Queuefrompyalgs.data_structures.commons.priority_queueimportMaxPQpq=MaxPQ.create()pq.enqueue(10)pq.enqueue(5)pq.enqueue(12)pq.enqueue(14)pq.enqueue(2)printpq.is_empty()printpq.size()print[iforiinpq.iterate()]deleted=pq.del_max()printdeletedSymbol Table using Binary Search Treefrompyalgs.data_structures.commons.binary_search_treeimportBinarySearchTreebst=BinarySearchTree.create()bst.put("one",1)bst.put("two",2)bst.put("three",3)bst.put("six",6)bst.put("ten",10)forkeyinbst.keys():print(key)printbst.get("one"))printbst.contains_key("two")printbst.size()printbst.is_empty()bst.delete("one")Symbol Table using Left Leaning Red Black Treefrompyalgs.data_structures.commons.binary_search_treeimportBinarySearchTreebst=BinarySearchTree.create_red_black_tree()bst.put("one",1)bst.put("two",2)bst.put("three",3)bst.put("six",6)bst.put("ten",10)printbst.get("one"))printbst.contains_key("two")forkeyinbst.keys():print(key)printbst.size()printbst.is_empty()bst.delete("one")Symbol Table using Hashed Mapfrompyalgs.data_structures.commons.hashed_mapimportHashedMapmap=HashedMap.create()map.put("one",1)map.put("two",2)map.put("three",3)map.put("six",6)map.put("ten",10)printmap.get("one"))printmap.contains_key("two")forkeyinmap.keys():print(key)printmap.size()printmap.is_empty()map.delete("one")Symbol Table using Hashed Setfrompyalgs.data_structures.commons.hashed_setimportHashedSetset=HashedSet.create()set.add("one")set.add("two")set.add("three")set.add("six")set.add("ten")printset.contains("two")forkeyinset.iterate():print(key)printset.size()printset.is_empty()set.delete("one")Undirected Graphfrompyalgs.data_structures.graphs.graphimportGraphdefcreate_graph():G=Graph(100)G.add_edge(1,2)G.add_edge(1,3)print([iforiinG.adj(1)])print([iforiinG.adj(2)])print([iforiinG.adj(3)])print(G.vertex_count())returnGDirected Graphfrompyalgs.data_structures.graphs.graphimportDigraphdefcreate_digraph():G=Digraph(100)G.add_edge(1,2)G.add_edge(1,3)print([iforiinG.adj(1)])print([iforiinG.adj(2)])print([iforiinG.adj(3)])print(G.vertex_count())returnGEdge Weighted Graphfrompyalgs.data_structures.graphs.graphimportEdgeWeightGraph,Edgedefcreate_edge_weighted_graph():g=EdgeWeightedGraph(8)g.add_edge(Edge(0,7,0.16))g.add_edge(Edge(2,3,0.17))g.add_edge(Edge(1,7,0.19))g.add_edge(Edge(0,2,0.26))g.add_edge(Edge(5,7,0.28))print([edgeforedgeinG.adj(3)])print(G.vertex_count())print(', '.join([edgeforedgeinG.edges()]))returngDirected Edge Weighted Graphfrompyalgs.data_structures.graphs.graphimportDirectedEdgeWeightedGraph,Edgedefcreate_edge_weighted_digraph():g=DirectedEdgeWeightedGraph(8)g.add_edge(Edge(0,1,5.0))g.add_edge(Edge(0,4,9.0))g.add_edge(Edge(0,7,8.0))g.add_edge(Edge(1,2,12.0))returngFlow Network ( for max-flow min-cut problem)frompyalgs.data_structures.graphs.graphimportFlowNetwork,FlowEdgedefcreate_flow_network():g=FlowNetwork(8)g.add_edge(FlowEdge(0,1,10))g.add_edge(FlowEdge(0,2,5))g.add_edge(FlowEdge(0,3,15))g.add_edge(FlowEdge(1,4,9))g.add_edge(FlowEdge(1,5,15))g.add_edge(FlowEdge(1,2,4))g.add_edge(FlowEdge(2,5,8))g.add_edge(FlowEdge(2,3,4))g.add_edge(FlowEdge(3,6,16))g.add_edge(FlowEdge(4,5,15))g.add_edge(FlowEdge(4,7,10))g.add_edge(FlowEdge(5,7,10))g.add_edge(FlowEdge(5,6,15))g.add_edge(FlowEdge(6,2,6))g.add_edge(FlowEdge(6,7,10))returngSymbol Table using R-ways Search Triesfrompyalgs.data_structures.strings.search_triesimportRWaySearchTriesst=RWaySearchTries()st.put("one",1)st.put("two",2)st.put("three",3)st.put("six",6)st.put("ten",10)forkeyinst.keys():print(key)printst.get("one"))printst.contains_key("two")printst.size()printst.is_empty()st.delete("one")forkeyinst.keys_with_prefix('t'):print(key)Symbol Table using Ternary Search Triesfrompyalgs.data_structures.strings.search_triesimportTernarySearchTriesst=TernarySearchTries()st.put("one",1)st.put("two",2)st.put("three",3)st.put("six",6)st.put("ten",10)forkeyinst.keys():print(key)printst.get("one"))printst.contains_key("two")printst.size()printst.is_empty()st.delete("one")forkeyinst.keys_with_prefix('t'):print(key)AlgorithmsUnion Findfrompyalgs.algorithms.commons.union_findimportUnionFinduf=UnionFind.create(10)uf.union(1,3)uf.union(2,4)uf.union(1,5)print(uf.connected(1,3))print(uf.connected(3,5))print(uf.connected(1,2))print(uf.connected(1,4))SortingThe sorting algorithms sort an array in ascending orderSelection Sortfrompyalgs.algorithms.commons.sortingimportSelectionSorta=[4,2,1]SelectionSort.sort(a)print(a)Insertion Sortfrompyalgs.algorithms.commons.sortingimportInsertionSorta=[4,2,1]InsertionSort.sort(a)print(a)Shell Sortfrompyalgs.algorithms.commons.sortingimportShellSorta=[4,2,1,23,4,5,6,7,8,9,20,11,13,34,66]ShellSort.sort(a)print(a)Merge Sortfrompyalgs.algorithms.commons.sortingimportMergeSorta=[4,2,1,23,4,5,6,7,8,9,20,11,13,34,66]MergeSort.sort(a)print(a)Quick Sortfrompyalgs.algorithms.commons.sortingimportQuickSorta=[4,2,1,23,4,5,6,7,8,9,20,11,13,34,66]QuickSort.sort(a)print(a)3-Ways Quick Sortfrompyalgs.algorithms.commons.sortingimportThreeWayQuickSorta=[4,2,1,23,4,5,6,7,8,9,20,11,13,34,66]ThreeWayQuickSort.sort(a)print(a)Heap Sortfrompyalgs.algorithms.commons.sortingimportHeapSorta=[4,2,1,23,4,5,6,7,8,9,20,11,13,34,66]HeapSort.sort(a)print(a)SelectionBinary Selectionfrompyalgs.algorithms.commons.selectingimportBinarySelectionfrompyalgs.algorithms.commons.utilimportis_sorteda=[1,2,13,22,123]assertis_sorted(a)printBinarySelection.index_of(a,13)ShuffleKnuth Shufflefrompyalgs.algorithms.commons.shufflingimportKnuthShufflea=[1,2,13,22,123]KnuthShuffle.shuffle(a)print(a)GraphDepth First Searchfrompyalgs.algorithms.graphs.searchimportDepthFirstSearchg=create_graph()s=0dfs=DepthFirstSearch(g,s)forvinrange(1,g.vertex_count()):ifdfs.hasPathTo(v):print(str(s)+' is connected to '+str(v))print('path is '+' => '.join([str(i)foriindfs.pathTo(v)]))Breadth First Searchfrompyalgs.algorithms.graphs.searchimportBreadthFirstSearchg=create_graph()s=0dfs=BreadthFirstSearch(g,s)forvinrange(1,g.vertex_count()):ifdfs.hasPathTo(v):print(str(s)+' is connected to '+str(v))print('path is '+' => '.join([str(i)foriindfs.pathTo(v)]))Connected ComponentsThis is for undirected graphfrompyalgs.algorithms.graphs.connectivityimportConnectedComponentsG=create_graph()cc=ConnectedComponents(G)print('connected component count: '+str(cc.count()))forvinrange(G.vertex_count()):print('id['+str(v)+']: '+str(cc.id(v)))forvinrange(G.vertex_count()):r=randint(0,G.vertex_count()-1)ifcc.connected(v,r):print(str(v)+' is connected to '+str(r))Strongly Connected ComponentsThis is for directed graphfrompyalgs.algorithms.graphs.connectivityimportStronglyConnectedComponentsG=create_graph()cc=StronglyConnectedComponents(G)print('strongly connected component count: '+str(cc.count()))forvinrange(G.vertex_count()):print('id['+str(v)+']: '+str(cc.id(v)))forvinrange(G.vertex_count()):r=randint(0,G.vertex_count()-1)ifcc.connected(v,r):print(str(v)+' is connected to '+str(r))Topological Sortfrompyalgs.algorithms.graphs.topological_sortimportDepthFirstOrderG=create_graph()topological_sort=DepthFirstOrder(G)print(' => '.join([str(i)foriintopological_sort.postOrder()]))Minimum Spanning Tree (Kruskal)frompyalgs.algorithms.graphs.minimum_spanning_treesimportKruskalMSTg=create_edge_weighted_graph()mst=KruskalMST(g)tree=mst.spanning_tree()foreintree:print(e)Minimum Spanning Tree (Prim Lazy)frompyalgs.algorithms.graphs.minimum_spanning_treesimportLazyPrimMSTg=create_edge_weighted_graph()mst=LazyPrimMST(g)tree=mst.spanning_tree()foreintree:print(e)Minimum Spanning Tree (Prim Eager)frompyalgs.algorithms.graphs.minimum_spanning_treesimportEagerPrimMSTg=create_edge_weighted_graph()mst=EagerPrimMST(g)tree=mst.spanning_tree()foreintree:print(e)Directed Cycle Detection:frompyalgs.algorithms.graphs.directed_cycleimportDirectedCycledag=create_dag()dc=DirectedCycle(dag)assertFalse(dc.hasCycle())Shortest Path (Dijkstra)frompyalgs.algorithms.graphs.shortest_pathimportDijkstraShortestPathg=create_edge_weighted_digraph()s=0dijkstra=DijkstraShortestPath(g,s)forvinrange(1,g.vertex_count()):ifdijkstra.hasPathTo(v):print(str(s)+' is connected to '+str(v))print('shortest path is '+' .. '.join([str(i)foriindijkstra.shortestPathTo(v)]))print('path length is '+str(dijkstra.path_length_to(v)))Shortest Path (Topological Sort)frompyalgs.algorithms.graphs.shortest_pathimportTopologicalSortShortestPathfrompyalgs.algorithms.graphs.directed_cycleimportDirectedCycleg=create_edge_weighted_digraph()assertnotDirectedCycle(g).hasCycle()s=0dijkstra=TopologicalSortShortestPath(g,s)forvinrange(1,g.vertex_count()):ifdijkstra.hasPathTo(v):print(str(s)+' is connected to '+str(v))print('shortest path is '+' .. '.join([str(i)foriindijkstra.shortestPathTo(v)]))print('path length is '+str(dijkstra.path_length_to(v)))Shortest Path (Bellman-Ford for positive and negative edge graph)frompyalgs.algorithms.graphs.shortest_pathimportBellmanFordShortestPathfrompyalgs.algorithms.graphs.directed_cycleimportDirectedCycleg=create_edge_weighted_digraph()s=0dijkstra=BellmanFordShortestPath(g,s)forvinrange(1,g.vertex_count()):ifdijkstra.hasPathTo(v):print(str(s)+' is connected to '+str(v))print('shortest path is '+' .. '.join([str(i)foriindijkstra.shortestPathTo(v)]))print('path length is '+str(dijkstra.path_length_to(v)))MaxFlow MinCut (Ford-Fulkerson)frompyalgs.algorithms.graphs.max_flowimportFordFulkersonMaxFlownetwork=create_flow_network()ff=FordFulkersonMaxFlow(network,0,7)print('max-flow: '+str(ff.max_flow_value()))StringsLongest Repeated Substringfrompyalgs.algorithms.strings.longest_repeated_substringimportLongestRepeatedSubstringSearchstart,len=LongestRepeatedSubstringSearch.lrs('Hello World','World Record')print('Hello World'[start:(start+len+1)])Sort (LSD)frompyalgs.algorithms.strings.sortingimportLSDLSD.sort(['good','cool','done','come'])Sort (MSD)frompyalgs.algorithms.strings.sortingimportMSDwords='more details are provided in the docs for implementation, complexities and further info'.split(' ')print(words)MSD.sort(words)print(words)Sort (3-Ways String Quick Sort)frompyalgs.algorithms.strings.sortingimportString3WayQuickSortwords='more details are provided in the docs for implementation, complexities and further info'.split(' ')print(words)String3WayQuickSort.sort(words)print(words)Substring Search (Brute force)frompyalgs.algorithms.strings.substring_searchimportBruteForceSubstringSearchss=BruteForceSubstringSearch('find')print(ss.search_in('I can find it here'))print(ss.search_in('It is not here'))Substring Search (Rabin Karp)frompyalgs.algorithms.strings.substring_searchimportRabinKarpss=RabinKarp('find')print(ss.search_in('I can find it here'))print(ss.search_in('It is not here'))Substring Search (Boyer Moore)frompyalgs.algorithms.strings.substring_searchimportBoyerMooress=BoyerMoore('find')print(ss.search_in('I can find it here'))print(ss.search_in('It is not here'))Substring Search (Knuth Morris Pratt)frompyalgs.algorithms.strings.substring_searchimportKnuthMorrisPrattss=KnuthMorrisPratt('find')print(ss.search_in('I can find it here'))print(ss.search_in('It is not here'))