diff --git a/BFS/python/bfs.py b/BFS/python/bfs.py index c4484476..842e8c18 100644 --- a/BFS/python/bfs.py +++ b/BFS/python/bfs.py @@ -16,7 +16,7 @@ def BFS(self, node): while queue: currentNode = queue.pop(0) - print currentNode + print(currentNode) children = self.graph[currentNode] for i in range(len(children)): @@ -39,5 +39,5 @@ def BFS(self, node): graph.addEdge(3, 2) graph.addEdge(3, 4) - print "Breadth First Search starting from vertex 0:" + print("Breadth First Search starting from vertex 0:") graph.BFS(0) diff --git a/BST/python/BinarySearchTree.py b/BST/python/BinarySearchTree.py index 37605658..e7151b66 100644 --- a/BST/python/BinarySearchTree.py +++ b/BST/python/BinarySearchTree.py @@ -5,42 +5,41 @@ @author: Daniel """ -# Binary Search Tree for an array of a single type +# Binary Search Tree for an array of a single type class BST: - def __init__(self, dataType): self._root = None self._dataType = dataType self._size = 0 - + def loadArray(self, inputArray): self.arr = inputArray - + def getSize(self): return self._size - + def isEmpty(self): return self._size == 0 - + def populateTree(self): for i in range(len(self.arr)): self.insert(self.arr[i]) - + def insert(self, value): if type(value) == self._dataType: itemNum = self._size newNode = Node(value, type(value), itemNum, None, None, None) - if (self._root == None): + if (self._root is None): self._root = newNode self._size += 1 return - + pointer = self._root currentVal = pointer.getData() while True: if value < currentVal: - if pointer.getLeft() == None: + if pointer.getLeft() is None: newNode.setParent(pointer) pointer.setLeft(newNode) self._size += 1 @@ -48,9 +47,9 @@ def insert(self, value): else: pointer = pointer.getLeft() currentVal = pointer.getData() - + elif value > currentVal: - if pointer.getRight() == None: + if pointer.getRight() is None: newNode.setParent(pointer) pointer.setRight(newNode) self._size += 1 @@ -58,94 +57,91 @@ def insert(self, value): else: pointer = pointer.getRight() currentVal = pointer.getData() - + elif value == currentVal: - print "Value already exists in BST." + print("Value already exists in BST.") return - + def search(self, value): if type(value) == self._dataType: - if (self._root == None): + if (self._root is None): return False - + pointer = self._root currentVal = pointer.getData() while True: if value < currentVal: - if pointer.getLeft() == None: + if pointer.getLeft() is None: return False - + pointer = pointer.getLeft() currentVal = pointer.getData() - + elif value > currentVal: - if pointer.getRight() == None: + if pointer.getRight() is None: return False - + pointer = pointer.getRight() currentVal = pointer.getData() - + elif value == currentVal: return pointer.getItemNum() - + def inOrderTraversal(self, node): - if node != None: + if node is not None: self.inOrderTraversal(node.getLeft()) self.sorted.append(node.getData()) self.inOrderTraversal(node.getRight()) - + def getSorted(self): self.sorted = list() self.inOrderTraversal(self._root) return self.sorted - + class Node: - def __init__(self, data, dataType, itemNum, parent, left, right): self._data = data - self._dataType = dataType # specifies type which node holds - self._itemNum = itemNum # position in parent array - self._parent = parent # link to parent node - self._left = left # link to left child node - self._right = right # link to right child node - - + self._dataType = dataType # specifies type which node holds + self._itemNum = itemNum # position in parent array + self._parent = parent # link to parent node + self._left = left # link to left child node + self._right = right # link to right child node + def getData(self): return self._data - + def setData(self, newData): if type(newData) == self._dataType: self._data = newData else: - print "Error, wrong data type." - + print("Error, wrong data type.") + def getItemNum(self): return self._itemNum - + def getParent(self): return self._parent - + def setParent(self, newParent): self._parent = newParent - + def getLeft(self): return self._left - + def setLeft(self, newLeft): self._left = newLeft - + def getRight(self): return self._right - + def setRight(self, newRight): self._right = newRight - + if __name__ == "__main__": bst = BST(int) - bst.loadArray((11,20,18,4,5,7,2,0)) + bst.loadArray((11, 20, 18, 4, 5, 7, 2, 0)) bst.populateTree() - print bst.search(18) - print bst.getSorted() - + print(bst.search(18)) + print(bst.getSorted()) diff --git a/BackTracking/Hamilton Path/hamilton.py b/BackTracking/Hamilton Path/hamilton.py index 8b63e7db..e9e9de02 100644 --- a/BackTracking/Hamilton Path/hamilton.py +++ b/BackTracking/Hamilton Path/hamilton.py @@ -1,96 +1,106 @@ +class Graph(): + def __init__(self, vertices): + self.graph = [[0 for column in range(vertices)] + for row in range(vertices)] + self.V = vertices -class Graph(): - def __init__(self, vertices): - self.graph = [[0 for column in range(vertices)]\ - for row in range(vertices)] - self.V = vertices - - def isSafe(self, v, pos, path): - # Check if current vertex and last vertex - # in path are adjacent - if self.graph[ path[pos-1] ][v] == 0: + def isSafe(self, v, pos, path): + # Check if current vertex and last vertex + # in path are adjacent + if self.graph[path[pos - 1]][v] == 0: return False - - # Check if current vertex not already in path - for vertex in path: - if vertex == v: + + # Check if current vertex not already in path + for vertex in path: + if vertex == v: return False - + return True - - def hamCycleUtil(self, path, pos): - - # base case: if all vertices are - # included in the path - if pos == self.V: - # Last vertex must be adjacent to the - # first vertex in path to make a cyle - if self.graph[ path[pos-1] ][ path[0] ] == 1: + + def hamCycleUtil(self, path, pos): + + # base case: if all vertices are + # included in the path + if pos == self.V: + # Last vertex must be adjacent to the + # first vertex in path to make a cyle + if self.graph[path[pos - 1]][path[0]] == 1: return True - else: + else: return False - - for v in range(1,self.V): - - if self.isSafe(v, pos, path) == True: - - path[pos] = v - - if self.hamCycleUtil(path, pos+1) == True: + + for v in range(1, self.V): + + if self.isSafe(v, pos, path) is True: + + path[pos] = v + + if self.hamCycleUtil(path, pos + 1) is True: return True - - # Remove current vertex if it doesn't - # lead to a solution + + # Remove current vertex if it doesn't + # lead to a solution path[pos] = -1 - + return False - - def hamCycle(self): - path = [-1] * self.V - - ''' Let us put vertex 0 as the first vertex - in the path. If there is a Hamiltonian Cycle, - then the path can be started from any point + + def hamCycle(self): + path = [-1] * self.V + ''' Let us put vertex 0 as the first vertex + in the path. If there is a Hamiltonian Cycle, + then the path can be started from any point of the cycle as the graph is undirected ''' path[0] = 0 - - if self.hamCycleUtil(path,1) == False: - print "Solution does not exist\n" + + if self.hamCycleUtil(path, 1) is False: + print("Solution does not exist\n") return False - - self.printSolution(path) + + self.printSolution(path) return True - - def printSolution(self, path): - print "Solution Exists: Following is one Hamiltonian Cycle" - for vertex in path: - print vertex, - print path[0], "\n" - -''' Let us create the following graph - (0)--(1)--(2) - | / \ | - | / \ | - | / \ | - (3)-------(4) ''' -g1 = Graph(5) -g1.graph = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], - [0, 1, 0, 0, 1,],[1, 1, 0, 0, 1], - [0, 1, 1, 1, 0], ] - -# Print the solution -g1.hamCycle(); - -''' Let us create the following graph - (0)--(1)--(2) - | / \ | - | / \ | - | / \ | - (3) (4) ''' -g2 = Graph(5) -g2.graph = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], - [0, 1, 0, 0, 1,], [1, 1, 0, 0, 0], - [0, 1, 1, 0, 0], ] - -# Print the solution -g2.hamCycle(); + + def printSolution(self, path): + print("Solution Exists: Following is one Hamiltonian Cycle") + for vertex in path: + print(vertex) + print(path[0], "\n") + + +''' +Let us create the following graph + (0)--(1)--(2) + | / \ | + | / \ | + | / \ | + (3)-------(4) +''' +g1 = Graph(5) +g1.graph = [ + [0, 1, 0, 1, 0], + [1, 0, 1, 1, 1], + [0, 1, 0, 0, 1], + [1, 1, 0, 0, 1], + [0, 1, 1, 1, 0], +] + +# Print the solution +g1.hamCycle() +''' +Let us create the following graph + (0)--(1)--(2) + | / \ | + | / \ | + | / \ | + (3) (4) +''' +g2 = Graph(5) +g2.graph = [ + [0, 1, 0, 1, 0], + [1, 0, 1, 1, 1], + [0, 1, 0, 0, 1], + [1, 1, 0, 0, 0], + [0, 1, 1, 0, 0], +] + +# Print the solution +g2.hamCycle() diff --git a/BackTracking/RatInAMaze/ratmaze.py b/BackTracking/RatInAMaze/ratmaze.py index 1d1d5cf6..82517bc1 100644 --- a/BackTracking/RatInAMaze/ratmaze.py +++ b/BackTracking/RatInAMaze/ratmaze.py @@ -1,80 +1,76 @@ +# Python3 program to solve Rat in a Maze +# problem using backracking -# Python3 program to solve Rat in a Maze -# problem using backracking - -# Maze size +# Maze size N = 4 - -# A utility function to print solution matrix sol -def printSolution( sol ): - - for i in sol: - for j in i: - print(str(j) + " ", end="") - print("") - -# A utility function to check if x,y is valid -# index for N*N Maze -def isSafe( maze, x, y ): - - if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: + + +# A utility function to print solution matrix sol +def printSolution(sol): + for i in sol: + for j in i: + print(str(j) + " ", end="") + print("") + + +# A utility function to check if x,y is valid +# index for N*N Maze +def isSafe(maze, x, y): + if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: return True - return False - -""" This function solves the Maze problem using Backtracking. - It mainly uses solveMazeUtil() to solve the problem. It - returns false if no path is possible, otherwise return - true and prints the path in the form of 1s. Please note - that there may be more than one solutions, this function - prints one of the feasable solutions. """ -def solveMaze( maze ): - - # Creating a 4 * 4 2-D list - sol = [ [ 0 for j in range(4) ] for i in range(4) ] - - if solveMazeUtil(maze, 0, 0, sol) == False: - print("Solution doesn't exist"); + + +def solveMaze(maze): + """ This function solves the Maze problem using Backtracking. + It mainly uses solveMazeUtil() to solve the problem. It + returns false if no path is possible, otherwise return + true and prints the path in the form of 1s. Please note + that there may be more than one solutions, this function + prints one of the feasable solutions. """ + + # Creating a 4 * 4 2-D list + sol = [[0 for j in range(4)] for i in range(4)] + + if solveMazeUtil(maze, 0, 0, sol) is False: + print("Solution doesn't exist") return False - - printSolution(sol) + + printSolution(sol) return True - -# A recursive utility function to solve Maze problem -def solveMazeUtil(maze, x, y, sol): - - #if (x,y is goal) return True - if x == N - 1 and y == N - 1: + + +# A recursive utility function to solve Maze problem +def solveMazeUtil(maze, x, y, sol): + + # if (x,y is goal) return True + if x == N - 1 and y == N - 1: sol[x][y] = 1 return True - - # Check if maze[x][y] is valid - if isSafe(maze, x, y) == True: - # mark x, y as part of solution path + + # Check if maze[x][y] is valid + if isSafe(maze, x, y) is True: + # mark x, y as part of solution path sol[x][y] = 1 - - # Move forward in x direction - if solveMazeUtil(maze, x + 1, y, sol) == True: + + # Move forward in x direction + if solveMazeUtil(maze, x + 1, y, sol) is True: return True - - # If moving in x direction doesn't give solution - # then Move down in y direction - if solveMazeUtil(maze, x, y + 1, sol) == True: + + # If moving in x direction doesn't give solution + # then Move down in y direction + if solveMazeUtil(maze, x, y + 1, sol) is True: return True - - # If none of the above movements work then - # BACKTRACK: unmark x,y as part of solution path + + # If none of the above movements work then + # BACKTRACK: unmark x,y as part of solution path sol[x][y] = 0 return False - -# Driver program to test above function -if __name__ == "__main__": - # Initialising the maze - maze = [ [1, 0, 0, 0], - [1, 1, 0, 1], - [0, 1, 0, 0], - [1, 1, 1, 1] ] - - solveMaze(maze) +# Driver program to test above function +if __name__ == "__main__": + # Initialising the maze + maze = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1]] + + solveMaze(maze) diff --git a/DFS/python/DFS.py b/DFS/python/DFS.py index 06ada611..c31f6fab 100644 --- a/DFS/python/DFS.py +++ b/DFS/python/DFS.py @@ -1,46 +1,45 @@ # Python program to print DFS traversal from a # given given graph from collections import defaultdict - + + # This class represents a directed graph using # adjacency list representation class Graph: - + # Constructor def __init__(self): - + # default dictionary to store graph self.graph = defaultdict(list) - + # function to add an edge to graph - def addEdge(self,u,v): + def addEdge(self, u, v): self.graph[u].append(v) - + # A function used by DFS - def DFSUtil(self,v,visited): - + def DFSUtil(self, v, visited): # Mark the current node as visited and print it - visited[v]= True - print v, - + visited[v] = True + print(v) + # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: - if visited[i] == False: + if visited[i] is False: self.DFSUtil(i, visited) - - + # The function to do DFS traversal. It uses # recursive DFSUtil() - def DFS(self,v): - + def DFS(self, v): + # Mark all the vertices as not visited - visited = [False]*(len(self.graph)) - + visited = [False] * (len(self.graph)) + # Call the recursive helper function to print # DFS traversal - self.DFSUtil(v,visited) - - + self.DFSUtil(v, visited) + + # Driver code # Create a graph given in the above diagram g = Graph() @@ -50,6 +49,6 @@ def DFS(self,v): g.addEdge(2, 0) g.addEdge(2, 3) g.addEdge(3, 3) - -print "Following is DFS from (starting from vertex 2)" + +print("Following is DFS from (starting from vertex 2)") g.DFS(2) diff --git a/DP/Coin Change Problem/NoOfWays.py b/DP/Coin Change Problem/NoOfWays.py index 1ff93650..550c9e9e 100644 --- a/DP/Coin Change Problem/NoOfWays.py +++ b/DP/Coin Change Problem/NoOfWays.py @@ -1,15 +1,18 @@ -# Recursive Python3 program for -# coin change problem. +# Recursive Python3 program for +# coin change problem. ''' Algorithm : Coin Change Problem (No of Ways) Type : DP -Problem -You have m types of coins available in infinite quantities where the value of each coin is given in the array C = [c0, c1....c m-1] . Can you determine the number of ways of making change for n units using the given types of coins? The order of coins doesn’t matter. +Problem +You have m types of coins available in infinite quantities where the value of +each coin is given in the array C = [c0, c1....c m-1] . +Can you determine the number of ways of making change for n units +using the given types of coins? The order of coins doesn’t matter. Example Input 4 3 1 2 3 -Output +Output 4 Explanation There are 4 ways to make n=4 with C=1,2,3 @@ -20,34 +23,35 @@ ''' -def count(S, m, n ): - # If n is 0 then there is 1 - # solution (do not include any coin) - if (n == 0): - return 1 +def count(S, m, n): + # If n is 0 then there is 1 + # solution (do not include any coin) + if (n == 0): + return 1 - # If n is less than 0 then no - # solution exists - if (n < 0): - return 0; + # If n is less than 0 then no + # solution exists + if (n < 0): + return 0 - # If there are no coins and n - # is greater than 0, then no - # solution exist - if (m <=0 and n >= 1): - return 0 + # If there are no coins and n + # is greater than 0, then no + # solution exist + if (m <= 0 and n >= 1): + return 0 - # count is sum of solutions (i) - # including S[m-1] (ii) excluding S[m-1] - return count( S, m - 1, n ) + count( S, m, n-S[m-1] ); + # count is sum of solutions (i) + # including S[m-1] (ii) excluding S[m-1] + return count(S, m - 1, n) + count(S, m, n - S[m - 1]) -# Driver program to test above function + +# Driver program to test above function # n , m = int(input()).split() n, m = [int(x) for x in input().split()] -arr = [int(x) for x in input().split()] -# m = len(arr) -print(count(arr, m, n)) +arr = [int(x) for x in input().split()] +# m = len(arr) +print(count(arr, m, n)) -# This code is contributed by Smitha Dinesh Semwal +# This code is contributed by Smitha Dinesh Semwal diff --git a/DP/Fibonacci/Fibonacci.py b/DP/Fibonacci/Fibonacci.py index ede01fb0..2a3dfe84 100644 --- a/DP/Fibonacci/Fibonacci.py +++ b/DP/Fibonacci/Fibonacci.py @@ -8,15 +8,15 @@ def fib(n): - if(n == 0): + if (n == 0): return 0 - elif(n == 1): + elif (n == 1): return 1 else: fib = [0, 1] - for i in range(2,n+1): - fib.append(fib[i-2] + fib[i-1]) + for i in range(2, n + 1): + fib.append(fib[i - 2] + fib[i - 1]) return fib[i] -print(fib(N)) \ No newline at end of file +print(fib(N)) diff --git a/DP/Fibonacci/fibonacci.py b/DP/Fibonacci/fibonacci.py index 310a0625..52f13a82 100644 --- a/DP/Fibonacci/fibonacci.py +++ b/DP/Fibonacci/fibonacci.py @@ -1,19 +1,22 @@ - # DP Approach for Fibonacci series ans = dict() + + def fibo(i): global ans - if i == 1:return 0 - elif i == 2:return 1 + if i == 1: + return 0 + elif i == 2: + return 1 elif i in ans: # print('found:', i, '=>', ans[i]) return ans[i] else: - r = fibo(i-1) + fibo(i-2) + r = fibo(i - 1) + fibo(i - 2) ans[i] = r return r - + + index = int(input('enter the index?')) print(fibo(index)) - diff --git a/DP/Knapsack/0-1Knapsack.py b/DP/Knapsack/0-1Knapsack.py index ea4f8087..922120b2 100644 --- a/DP/Knapsack/0-1Knapsack.py +++ b/DP/Knapsack/0-1Knapsack.py @@ -1,28 +1,28 @@ -# Returns the maximum value that can be put in a knapsack of -# capacity W -def knapSack(W , wt , val , n): - - # Base Case - if n == 0 or W == 0 : +def knapSack(W, wt, val, n): + ''' + Returns the maximum value that can be put in a knapsack of + capacity W + ''' + # Base Case + if n == 0 or W == 0: return 0 - - # If weight of the nth item is more than Knapsack of capacity - # W, then this item cannot be included in the optimal solution - if (wt[n-1] > W): - return knapSack(W , wt , val , n-1) - - # return the maximum of two cases: - # (1) nth item included - # (2) not included - else: - return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1), - knapSack(W , wt , val , n-1)) - -# end of function knapSack - -# To test above function -val = [60, 100, 120] -wt = [10, 20, 30] + + # If weight of the nth item is more than Knapsack of capacity + # W, then this item cannot be included in the optimal solution + if (wt[n - 1] > W): + return knapSack(W, wt, val, n - 1) + + # return the maximum of two cases: + # (1) nth item included + # (2) not included + else: + return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), + knapSack(W, wt, val, n - 1)) + + +# To test above function +val = [60, 100, 120] +wt = [10, 20, 30] W = 50 -n = len(val) -print knapSack(W , wt , val , n) +n = len(val) +print(knapSack(W, wt, val, n)) diff --git a/DP/LongestCommonSubsequence/LCS.py b/DP/LongestCommonSubsequence/LCS.py index e60ef5ec..88540b76 100644 --- a/DP/LongestCommonSubsequence/LCS.py +++ b/DP/LongestCommonSubsequence/LCS.py @@ -1,22 +1,21 @@ -def lcs(X , Y): - # find the length of the strings - m = len(X) - n = len(Y) - - # declaring the array for storing the dp values - L = [[None]*(n+1) for i in xrange(m+1)] - - """Following steps build L[m+1][n+1] in bottom up fashion - Note: L[i][j] contains length of LCS of X[0..i-1] +def lcs(X, Y): + # find the length of the strings + m = len(X) + n = len(Y) + + # declaring the array for storing the dp values + L = [[None] * (n + 1) for i in range(m + 1)] + """Following steps build L[m+1][n+1] in bottom up fashion + Note: L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]""" - for i in range(m+1): - for j in range(n+1): - if i == 0 or j == 0 : + for i in range(m + 1): + for j in range(n + 1): + if i == 0 or j == 0: L[i][j] = 0 - elif X[i-1] == Y[j-1]: - L[i][j] = L[i-1][j-1]+1 - else: - L[i][j] = max(L[i-1][j] , L[i][j-1]) - - # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] - return L[m][n] + elif X[i - 1] == Y[j - 1]: + L[i][j] = L[i - 1][j - 1] + 1 + else: + L[i][j] = max(L[i - 1][j], L[i][j - 1]) + + # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1] + return L[m][n] diff --git a/DP/LongestIncreasingSubsequence/LIC.py b/DP/LongestIncreasingSubsequence/LIC.py index 3054be98..5c938cce 100644 --- a/DP/LongestIncreasingSubsequence/LIC.py +++ b/DP/LongestIncreasingSubsequence/LIC.py @@ -1,60 +1,61 @@ -# A naive Python implementation of LIS problem - -""" To make use of recursive calls, this function must return -two things: -1) Length of LIS ending with element arr[n-1]. We use -max_ending_here for this purpose -2) Overall maximum as the LIS may end with an element -before arr[n-1] max_ref is used this purpose. -The value of LIS of full array of size n is stored in +# A naive Python implementation of LIS problem +""" To make use of recursive calls, this function must return +two things: +1) Length of LIS ending with element arr[n-1]. We use +max_ending_here for this purpose +2) Overall maximum as the LIS may end with an element +before arr[n-1] max_ref is used this purpose. +The value of LIS of full array of size n is stored in *max_ref which is our final result """ -# global variable to store the maximum -global maximum +# global variable to store the maximum +global maximum -def _lis(arr , n ): - # to allow the access of global variable - global maximum +def _lis(arr, n): - # Base Case - if n == 1 : + # to allow the access of global variable + global maximum + + # Base Case + if n == 1: return 1 - # maxEndingHere is the length of LIS ending with arr[n-1] + # maxEndingHere is the length of LIS ending with arr[n-1] maxEndingHere = 1 - - """Recursively get all LIS ending with arr[0], arr[1]..arr[n-2] - IF arr[n-1] is maller than arr[n-1], and max ending with + """Recursively get all LIS ending with arr[0], arr[1]..arr[n-2] + IF arr[n-1] is maller than arr[n-1], and max ending with arr[n-1] needs to be updated, then update it""" - for i in range(1, n): - res = _lis(arr , i) - if arr[i-1] < arr[n-1] and res+1 > maxEndingHere: - maxEndingHere = res +1 + for i in range(1, n): + res = _lis(arr, i) + if arr[i - 1] < arr[n - 1] and res + 1 > maxEndingHere: + maxEndingHere = res + 1 - # Compare maxEndingHere with overall maximum. And - # update the overall maximum if needed - maximum = max(maximum , maxEndingHere) + # Compare maxEndingHere with overall maximum. And + # update the overall maximum if needed + maximum = max(maximum, maxEndingHere) - return maxEndingHere + return maxEndingHere -def lis(arr): - # to allow the access of global variable - global maximum +def lis(arr): - # lenght of arr - n = len(arr) + # to allow the access of global variable + global maximum - # maximum variable holds the result + # lenght of arr + n = len(arr) + + # maximum variable holds the result maximum = 1 - # The function _lis() stores its result in maximum - _lis(arr , n) + # The function _lis() stores its result in maximum + _lis(arr, n) + + return maximum - return maximum -# Driver program to test the above function -arr = [10 , 22 , 9 , 33 , 21 , 50 , 41 , 60] -n = len(arr) +# Driver program to test the above function +arr = [10, 22, 9, 33, 21, 50, 41, 60] +n = len(arr) print("Length of lis is ", lis(arr)) diff --git a/DP/MatrixChain_multiplication/matrixchain_mul.py b/DP/MatrixChain_multiplication/matrixchain_mul.py index ec172127..281883ce 100644 --- a/DP/MatrixChain_multiplication/matrixchain_mul.py +++ b/DP/MatrixChain_multiplication/matrixchain_mul.py @@ -1,36 +1,35 @@ -import sys - -# Matrix A[i] has dimension p[i-1] x p[i] -# for i = 1..n -def MatrixChainOrder(p, i, j): - - if i == j: +import sys + + +def MatrixChainOrder(p, i, j): + ''' + Matrix A[i] has dimension p[i-1] x p[i] + for i = 1..n + ''' + if i == j: return 0 - - _min = sys.maxsize - - # place parenthesis at different places - # between first and last matrix, - # recursively calculate count of - # multiplications for each parenthesis - # placement and return the minimum count - for k in range(i, j): - - count = (MatrixChainOrder(p, i, k) - + MatrixChainOrder(p, k+1, j) - + p[i-1] * p[k] * p[j]) - - if count < _min: - _min = count; - - - # Return minimum count - return _min; - - -# Driver program to test above function -arr = [1, 2, 3, 4, 3]; -n = len(arr); - -print("Minimum number of multiplications is ", - MatrixChainOrder(arr, 1, n-1)); \ No newline at end of file + + _min = sys.maxsize + + # place parenthesis at different places + # between first and last matrix, + # recursively calculate count of + # multiplications for each parenthesis + # placement and return the minimum count + for k in range(i, j): + + count = (MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + + p[i - 1] * p[k] * p[j]) + + if count < _min: + _min = count + + # Return minimum count + return _min + + +# Driver program to test above function +arr = [1, 2, 3, 4, 3] +n = len(arr) + +print("Minimum number of multiplications is ", MatrixChainOrder(arr, 1, n - 1)) diff --git a/DP/Maximum Sum Increasing Subsequence/MaximumSumIncreasingSubsequence.py b/DP/Maximum Sum Increasing Subsequence/MaximumSumIncreasingSubsequence.py index a2393780..aba282ad 100644 --- a/DP/Maximum Sum Increasing Subsequence/MaximumSumIncreasingSubsequence.py +++ b/DP/Maximum Sum Increasing Subsequence/MaximumSumIncreasingSubsequence.py @@ -2,57 +2,58 @@ import sys from copy import copy -fstd="test2" +fstd = "test2" sys.stdin = open('%s.txt' % fstd, 'r') input = sys.stdin.readline -# DP based Python -# implementation of Maximum Sum -# Increasing Subsequence (MSIS) -# problem - +# DP based Python +# implementation of Maximum Sum +# Increasing Subsequence (MSIS) +# problem + + # constructMaxSumIS() returns the tupple: # ( max sum of increasing subsequence, found subsequence ) -def constructMaxSumIS(arr): +def constructMaxSumIS(arr): N = len(arr) - + # L[i] stores the Maximum Sum Increasing Subsequence that ends with arr[i] - L=[ [] for _ in range(N) ] + L = [[] for _ in range(N)] # L[0] is equal to arr[0] L[0].append(arr[0]) - + # msis[i] stores the Maximum Sum of Increasing Subsequence that # ends with arr[i] - msis = [0]*N - # Initialize msis values - msis[0]=arr[0] - - # Compute maximum sum - # values in bottom up manner - for i in range(1, N): - for j in range(i): - if (arr[i] > arr[j]) and (msis[i] < msis[j]): + msis = [0] * N + # Initialize msis values + msis[0] = arr[0] + + # Compute maximum sum + # values in bottom up manner + for i in range(1, N): + for j in range(i): + if (arr[i] > arr[j]) and (msis[i] < msis[j]): msis[i] = msis[j] L[i] = copy(L[j]) L[i].append(arr[i]) - msis[i]+=arr[i] + msis[i] += arr[i] + + # Find max + maxIndex = max(range(N), key=lambda i: msis[i]) + return (msis[maxIndex], L[maxIndex]) - # Find max - maxIndex=max(range(N), key=lambda i:msis[i]) - return (msis[maxIndex],L[maxIndex]) if __name__ == "__main__": print("Input sequence:") - A=[] - while(True): - line=input().strip() + A = [] + while (True): + line = input().strip() try: - num=int(line) + num = int(line) except ValueError: break A.append(num) print(A) - res=constructMaxSumIS(A) + res = constructMaxSumIS(A) print("Max sum is {}".format(res[0])) print("Found sequence is: {} ".format(res[1])) - \ No newline at end of file diff --git a/DP/subset_sum problem/subsetSum.py b/DP/subset_sum problem/subsetSum.py index ec97a85d..acc66314 100644 --- a/DP/subset_sum problem/subsetSum.py +++ b/DP/subset_sum problem/subsetSum.py @@ -1,36 +1,38 @@ -# Returns true if there exists a subset -# with given sum in arr[] - -def isSubsetSum(arr, n, sum): - - # The value of subset[i%2][j] will be true - # if there exists a subset of sum j in - # arr[0, 1, ...., i-1] - subset = [ [False for j in range(sum + 1)] for i in range(3) ] - - for i in range(n + 1): - for j in range(sum + 1): - # A subset with sum 0 is always possible - if (j == 0): +def isSubsetSum(arr, n, sum): + ''' + Returns true if there exists a subset + with given sum in arr[] + ''' + + # The value of subset[i%2][j] will be true + # if there exists a subset of sum j in + # arr[0, 1, ...., i-1] + subset = [[False for j in range(sum + 1)] for i in range(3)] + + for i in range(n + 1): + for j in range(sum + 1): + # A subset with sum 0 is always possible + if (j == 0): subset[i % 2][j] = True - - # If there exists no element no sum - # is possible - elif (i == 0): + + # If there exists no element no sum + # is possible + elif (i == 0): subset[i % 2][j] = False - elif (arr[i - 1] <= j): - subset[i % 2][j] = subset[(i + 1) % 2][j - arr[i - 1]] or subset[(i + 1) - % 2][j] - else: - subset[i % 2][j] = subset[(i + 1) % 2][j] - - return subset[n % 2][sum] - -# Driver code -arr = [ 6, 2, 5 ] + elif (arr[i - 1] <= j): + subset[i % 2][j] = subset[ + (i + 1) % 2][j - arr[i - 1]] or subset[(i + 1) % 2][j] + else: + subset[i % 2][j] = subset[(i + 1) % 2][j] + + return subset[n % 2][sum] + + +# Driver code +arr = [6, 2, 5] sum = 7 -n = len(arr) -if (isSubsetSum(arr, n, sum) == True): - print ("There exists a subset with given sum") -else: - print ("No subset exists with given sum") \ No newline at end of file +n = len(arr) +if (isSubsetSum(arr, n, sum) is True): + print("There exists a subset with given sum") +else: + print("No subset exists with given sum") diff --git a/Data Structures/Fenwick_tree/fenwick.py b/Data Structures/Fenwick_tree/fenwick.py index 9620499c..1645b611 100644 --- a/Data Structures/Fenwick_tree/fenwick.py +++ b/Data Structures/Fenwick_tree/fenwick.py @@ -4,14 +4,15 @@ Oct 7 18 9:42:35 PM """ + class fenwick: """Fenwick Tree""" - - #def __init__(self, list): - # """Initialize BIT with list in O(n*log(n))""" - # self.array = [0] * (len(list) + 1) - # for idx, val in enumerate(list): - # self.update(idx, val) + + # def __init__(self, list): + # """Initialize BIT with list in O(n*log(n))""" + # self.array = [0] * (len(list) + 1) + # for idx, val in enumerate(list): + # self.update(idx, val) def __init__(self, list): """"Initialize BIT with list in O(n)""" @@ -48,18 +49,22 @@ def update(self, idx, add): print('Array: [{}]'.format(', '.join(map(str, array)))) print() - print('Prefix sum of first {} elements: {}'.format(13, bit.prefix_query(12))) + print('Prefix sum of first {} elements: {}'.format(13, + bit.prefix_query(12))) print('Prefix sum of first {} elements: {}'.format(7, bit.prefix_query(6))) - print('Range sum from pos {} to pos {}: {}'.format(1, 5, bit.range_query(1, 5))) + print('Range sum from pos {} to pos {}: {}'.format(1, 5, + bit.range_query(1, 5))) print() - + bit.update(4, 2) print('Add {} to element at pos {}'.format(2, 4)) new_array = [bit.range_query(idx, idx) for idx in range(len(array))] print('Array: [{}]'.format(', '.join(map(str, new_array)))) print() - print('Prefix sum of first {} elements: {}'.format(13, bit.prefix_query(12))) + print('Prefix sum of first {} elements: {}'.format(13, + bit.prefix_query(12))) print('Prefix sum of first {} elements: {}'.format(7, bit.prefix_query(6))) - print('Range sum from pos {} to pos {}: {}'.format(1, 5, bit.range_query(1, 5))) - print() \ No newline at end of file + print('Range sum from pos {} to pos {}: {}'.format(1, 5, + bit.range_query(1, 5))) + print() diff --git a/Data Structures/Queue/Implement queue using stack/Python/queue_using_stack.py b/Data Structures/Queue/Implement queue using stack/Python/queue_using_stack.py index d22edd53..b0be608c 100644 --- a/Data Structures/Queue/Implement queue using stack/Python/queue_using_stack.py +++ b/Data Structures/Queue/Implement queue using stack/Python/queue_using_stack.py @@ -8,9 +8,11 @@ - Peek O(1) ''' + class UnderflowException(Exception): pass + class Stack(object): def __init__(self): self._stack = [] @@ -52,7 +54,8 @@ def peek(self): if self.is_empty(): return -1 return self._stack[self.__top] - + + ''' Algorithm: - First we pop all the elements from stack one and store them in stack two @@ -63,21 +66,22 @@ def peek(self): - Same can be done with dequeue, in that case time complexity of enqueue will be O(1) ''' + class QueueUsingStack(object): def __init__(self): self._stack_one = Stack() self._stack_two = Stack() - + def __str__(self): return self._stack_one.__str__() - + def enqueue(self, element): ''' :param element: element to be enqueued in the queue ''' while not self._stack_one.is_empty(): self._stack_two.push(self._stack_one.pop()) - + self._stack_one.push(element) while not self._stack_two.is_empty(): @@ -89,6 +93,7 @@ def dequeue(self): raise UnderflowException return self._stack_one.pop() + if __name__ == '__main__': queue = QueueUsingStack() for i in range(10): diff --git a/Graph/DijkstrasSPT/python/Dadjacencylist.py b/Graph/DijkstrasSPT/python/Dadjacencylist.py index 56f3762b..9ea4da71 100644 --- a/Graph/DijkstrasSPT/python/Dadjacencylist.py +++ b/Graph/DijkstrasSPT/python/Dadjacencylist.py @@ -1,176 +1,148 @@ -# Python program for Dijkstra's shortest path algorithm for adjacency list representation of graph - +# Python program for Dijkstra's shortest path algorithm for adjacency list +# representation of graph from collections import defaultdict import sys - + + class Heap(): - def __init__(self): self.array = [] self.size = 0 self.pos = [] - + def newMinHeapNode(self, v, dist): minHeapNode = [v, dist] return minHeapNode - - # A utility function to swap two nodes + + # A utility function to swap two nodes # of min heap. Needed for min heapify - def swapMinHeapNode(self,a, b): + def swapMinHeapNode(self, a, b): t = self.array[a] self.array[a] = self.array[b] self.array[b] = t - - + def minHeapify(self, idx): smallest = idx - left = 2*idx + 1 - right = 2*idx + 2 - - if left < self.size and self.array[left][1] \ - < self.array[smallest][1]: + left = 2 * idx + 1 + right = 2 * idx + 2 + + if left < self.size and self.array[left][1] < self.array[smallest][1]: smallest = left - - if right < self.size and self.array[right][1]\ - < self.array[smallest][1]: + + if right < self.size and self.array[right][1] \ + < self.array[smallest][1]: smallest = right - - + if smallest != idx: - + # Swap positions - self.pos[ self.array[smallest][0] ] = idx - self.pos[ self.array[idx][0] ] = smallest - - + self.pos[self.array[smallest][0]] = idx + self.pos[self.array[idx][0]] = smallest + self.swapMinHeapNode(smallest, idx) - + self.minHeapify(smallest) - - + def extractMin(self): - - - if self.isEmpty() == True: + + if self.isEmpty() is True: return - - + root = self.array[0] - - + lastNode = self.array[self.size - 1] self.array[0] = lastNode - - + self.pos[lastNode[0]] = 0 self.pos[root[0]] = self.size - 1 - - + self.size -= 1 self.minHeapify(0) - + return root - + def isEmpty(self): return True if self.size == 0 else False - + def decreaseKey(self, v, dist): - # Get the index of v in heap array - i = self.pos[v] - - self.array[i][1] = dist - - + while i > 0 and self.array[i][1] < self.array[(i - 1) / 2][1]: - # Swap this node with its parent - self.pos[ self.array[i][0] ] = (i-1)/2 - self.pos[ self.array[(i-1)/2][0] ] = i - self.swapMinHeapNode(i, (i - 1)/2 ) - + self.pos[self.array[i][0]] = (i - 1) / 2 + self.pos[self.array[(i - 1) / 2][0]] = i + self.swapMinHeapNode(i, (i - 1) / 2) + # move to parent index - i = (i - 1) / 2; - - # A utility function to check if a given + i = (i - 1) / 2 + + # A utility function to check if a given # vertex 'v' is in min heap or not def isInMinHeap(self, v): - + if self.pos[v] < self.size: return True return False - - + + def printArr(dist, n): - print "Vertex\tDistance from source" + print("Vertex\tDistance from source") for i in range(n): - print "%d\t\t%d" % (i,dist[i]) - - + print("%d\t\t%d" % (i, dist[i])) + + class Graph(): - def __init__(self, V): self.V = V self.graph = defaultdict(list) - - + def addEdge(self, src, dest, weight): - - + newNode = [dest, weight] self.graph[src].insert(0, newNode) - - + newNode = [src, weight] self.graph[dest].insert(0, newNode) - - + def dijkstra(self, src): - + V = self.V # Get the number of vertices in graph - dist = [] # dist values used to pick minimum - # weight edge in cut - + dist = [] # dist values used to pick minimum + # weight edge in cut + minHeap = Heap() - + for v in range(V): dist.append(sys.maxint) - minHeap.array.append( minHeap.newMinHeapNode(v, dist[v]) ) + minHeap.array.append(minHeap.newMinHeapNode(v, dist[v])) minHeap.pos.append(v) - - + minHeap.pos[src] = src dist[src] = 0 minHeap.decreaseKey(src, dist[src]) - - - minHeap.size = V; - - - while minHeap.isEmpty() == False: - - + + minHeap.size = V + + while minHeap.isEmpty() is False: + newHeapNode = minHeap.extractMin() u = newHeapNode[0] - - + for pCrawl in self.graph[u]: - + v = pCrawl[0] - - + if minHeap.isInMinHeap(v) and dist[u] != sys.maxint and \ pCrawl[1] + dist[u] < dist[v]: - dist[v] = pCrawl[1] + dist[u] - - - minHeap.decreaseKey(v, dist[v]) - - printArr(dist,V) - - + dist[v] = pCrawl[1] + dist[u] + + minHeap.decreaseKey(v, dist[v]) + + printArr(dist, V) + + # Driver program to test the above functions graph = Graph(9) graph.addEdge(0, 1, 4) diff --git a/Hashing/3_Sum/3_sum.py b/Hashing/3_Sum/3_sum.py index a46368f7..d2bac843 100644 --- a/Hashing/3_Sum/3_sum.py +++ b/Hashing/3_Sum/3_sum.py @@ -1,21 +1,21 @@ def find_triplet(arr): - found = False - n = len(arr) - for i in range(n - 1): - set_val = set() - for j in range(i + 1, n): - x = - (arr[i] + arr[j]) - if x in set_val: - print('{} {} {}'.format(x, arr[i], arr[j])) - found = True - else: - set_val.add(arr[j]) + found = False + n = len(arr) + for i in range(n - 1): + set_val = set() + for j in range(i + 1, n): + x = -(arr[i] + arr[j]) + if x in set_val: + print('{} {} {}'.format(x, arr[i], arr[j])) + found = True + else: + set_val.add(arr[j]) - if not found: - print('No triplet found!') + if not found: + print('No triplet found!') # Driver program to test above function if __name__ == '__main__': - arr = [0, -1, 2, -3, 1] - find_triplet(arr) + arr = [0, -1, 2, -3, 1] + find_triplet(arr) diff --git a/Hashing/3_Sum/threeSum.py b/Hashing/3_Sum/threeSum.py index ef0a436b..c67090fa 100644 --- a/Hashing/3_Sum/threeSum.py +++ b/Hashing/3_Sum/threeSum.py @@ -5,17 +5,16 @@ nums = [-1, 0, 1, 2, -1, -4] hashTable = [] -result = [] # result containing duplicate values -finalresult = [] # stores final result without duplicate values +result = [] # result containing duplicate values +finalresult = [] # stores final result without duplicate values +for i in range(0, len(nums) - 2): -for i in range(0, len(nums)-2): - - for j in range(i+1, len(nums)-1): + for j in range(i + 1, len(nums) - 1): x = -(nums[i] + nums[j]) - if(x in hashTable): + if (x in hashTable): result.append([]) - result[len(result)-1].append(x) + result[len(result) - 1].append(x) result[len(result) - 1].append(nums[i]) result[len(result) - 1].append(nums[j]) else: @@ -26,4 +25,4 @@ if not result[i] in finalresult: finalresult.append(result[i]) -print(finalresult) \ No newline at end of file +print(finalresult) diff --git a/NetworkFlow/EdmundKarp/edmund_karp.py b/NetworkFlow/EdmundKarp/edmund_karp.py index c55ecd5e..04882f97 100644 --- a/NetworkFlow/EdmundKarp/edmund_karp.py +++ b/NetworkFlow/EdmundKarp/edmund_karp.py @@ -44,10 +44,11 @@ def BFSEK(E, C, s, t, F, P, M, BFSq): return M[t], P return 0, P + if __name__ == "__main__": E = [[1, 2], [2, 3], [3], []] # Adjacency Matrix - C = [[0, 1000000, 1000000, 0], [0, 0, 1, 1000000], - [0, 0, 0, 1000000], [0, 0, 0, 0]] # Capacity Matrix + C = [[0, 1000000, 1000000, 0], [0, 0, 1, 1000000], [0, 0, 0, 1000000], + [0, 0, 0, 0]] # Capacity Matrix s = 0 # Source t = 3 # Sink - print(EdmondsKarp(E, C, s, t)) \ No newline at end of file + print(EdmondsKarp(E, C, s, t)) diff --git a/Search/BinarySearch/BinarySearch.py b/Search/BinarySearch/BinarySearch.py index eb83634f..53f0ce46 100644 --- a/Search/BinarySearch/BinarySearch.py +++ b/Search/BinarySearch/BinarySearch.py @@ -1,22 +1,23 @@ -def Binary_search(arr,start_index,last_index,element): - mid =(int)(start_index+last_index)/2 - - if(start_index>last_index): - print "Element not found" - - elif (element>arr[mid]): - start_index = mid+1 - Binary_search(arr,start_index,last_index,element) - - elif (element last_index): + print("Element not found") + + elif (element > arr[mid]): + start_index = mid + 1 + Binary_search(arr, start_index, last_index, element) + + elif (element < arr[mid]): + last_index = mid - 1 + Binary_search(arr, start_index, last_index, element) + else: - print "element is present at index " + str(mid) - -arr = [2,14,19,21,99,210,512,1028,4443,5110] + print("element is present at index " + str(mid)) + + +arr = [2, 14, 19, 21, 99, 210, 512, 1028, 4443, 5110] element = 99 start_index = 0 -last_index = len(arr)-1 -Binary_search(arr,start_index,last_index,element) +last_index = len(arr) - 1 +Binary_search(arr, start_index, last_index, element) diff --git a/Search/LinearSearch/linear_search.py b/Search/LinearSearch/linear_search.py index 2b941826..153e5e6e 100644 --- a/Search/LinearSearch/linear_search.py +++ b/Search/LinearSearch/linear_search.py @@ -4,7 +4,7 @@ @author: KARAN """ -numbers =[] +numbers = [] n = int(input("Enter the total number of elements : ")) for i in range(n): numbers.append(int(input("Enter a number : "))) @@ -13,7 +13,7 @@ found = False for i in range(n): if key == numbers[i]: - print(key," found at index ",i+1," ! :)") - found=True + print(key, " found at index ", i + 1, " ! :)") + found = True if not found: - print(key," not found in the list! :(") + print(key, " not found in the list! :(") diff --git a/Sorting/CountingSort/python/CountingSort.py b/Sorting/CountingSort/python/CountingSort.py index 698f754b..9ee98e62 100644 --- a/Sorting/CountingSort/python/CountingSort.py +++ b/Sorting/CountingSort/python/CountingSort.py @@ -2,8 +2,8 @@ def countingSort(arr, k): m = k + 1 count = [0] * m - for a in arr: # count occurences + for a in arr: count[a] += 1 i = 0 for a in range(m): @@ -11,6 +11,8 @@ def countingSort(arr, k): arr[i] = a i += 1 return arr + + testArray = [473, 78, 92, 5, 18, 7, 65, 89] print("Before: " + str(testArray)) sortedArray = countingSort(testArray, 474) diff --git a/Sorting/HeapSort/python/Heapsort.py b/Sorting/HeapSort/python/Heapsort.py index 340fc080..0204ab0f 100755 --- a/Sorting/HeapSort/python/Heapsort.py +++ b/Sorting/HeapSort/python/Heapsort.py @@ -1,39 +1,41 @@ - # Worst Case: O(n log n) # Best Case: O(n log n) # Average Case: O(n log n) + def heapsort(a): heapify(a, len(a)) - end = len(a)-1 + end = len(a) - 1 while end > 0: a[end], a[0] = a[0], a[end] end -= 1 traverse(a, 0, end) + def heapify(a, count): - start = int((count-2)/2) + start = int((count - 2) / 2) while start >= 0: - traverse(a, start, count-1) + traverse(a, start, count - 1) start -= 1 + def traverse(a, start, end): root = start - while (root*2+1) <= end: + while (root * 2 + 1) <= end: child = root * 2 + 1 swap = root if a[swap] < a[child]: swap = child - if (child + 1) <= end and a[swap] < a[child+1]: - swap = child+1 + if (child + 1) <= end and a[swap] < a[child + 1]: + swap = child + 1 if swap != root: a[root], a[swap] = a[swap], a[root] root = swap else: return + if __name__ == "__main__": - a = [5,109,87,4,50,908,65,22,1,36] + a = [5, 109, 87, 4, 50, 908, 65, 22, 1, 36] heapsort(a) print(a) - diff --git a/Sorting/IndexSort/python/indexSort.py b/Sorting/IndexSort/python/indexSort.py index 30085610..ba104e60 100644 --- a/Sorting/IndexSort/python/indexSort.py +++ b/Sorting/IndexSort/python/indexSort.py @@ -1,21 +1,21 @@ - # get the number of elements in array number_of_elements = int(input()) -# input array +# input array array = list(map(int, input().split())) # get the maximum number in array # use that number as maximum possible index -arr = [-1] * ( max(array) + 1) +arr = [-1] * (max(array) + 1) # map the array in secondery array -for e in array:arr[e] += 1 +for e in array: + arr[e] += 1 # printing the sorted arrey -for index,e in enumerate(arr): +for index, e in enumerate(arr): # print the number only it was found in the array if e != -1: - - for _ in range(e+1): + + for _ in range(e + 1): print(index, end=' ') diff --git a/Sorting/InsertionSort/python/InsertionSort.py b/Sorting/InsertionSort/python/InsertionSort.py index 961cc5e0..467eb3bb 100755 --- a/Sorting/InsertionSort/python/InsertionSort.py +++ b/Sorting/InsertionSort/python/InsertionSort.py @@ -1,22 +1,21 @@ class InsertionSort: + def __init__(self, lst): + self.lst = lst - def __init__(self, lst): - self.lst = lst + def sort(self): + for i in range(1, len(self.lst)): + key = self.lst[i] + j = i - 1 + while j > -1 and self.lst[j] > key: + self.lst[j + 1] = self.lst[j] + j = j - 1 + self.lst[j + 1] = key - def sort(self): - for i in range(1,len(self.lst)): - key = self.lst[i] - j = i - 1 - while j > -1 and self.lst[j] > key: - self.lst[j+1] = self.lst[j] - j = j - 1 - self.lst[j + 1] = key - - def show(self): - return self.lst + def show(self): + return self.lst if __name__ == "__main__": - i = InsertionSort([5,4,3,2,1]) - i.sort(); - print i.show() + i = InsertionSort([5, 4, 3, 2, 1]) + i.sort() + print(i.show()) diff --git a/Sorting/MergeSort/python/MergeSort.py b/Sorting/MergeSort/python/MergeSort.py index 7d7c2b72..2275d1ae 100755 --- a/Sorting/MergeSort/python/MergeSort.py +++ b/Sorting/MergeSort/python/MergeSort.py @@ -1,44 +1,44 @@ class MergeSort: + def __init__(self, lst): + self.lst = lst - def __init__(self, lst): - self.lst = lst + def mergeSort(self, a): + midPoint = len(a) // 2 + if a[len(a) - 1] < a[0]: + left = self.mergeSort(a[:midPoint]) + right = self.mergeSort(a[midPoint:]) + return self.merge(left, right) + else: + return a - def mergeSort(self, a): - midPoint = len(a)//2 - if a[len(a)-1] < a[0]: - left = self.mergeSort(a[:midPoint]) - right = self.mergeSort(a[midPoint:]) - return self.merge(left, right) - else: - return a + def merge(self, left, right): + output = list() + leftCount, rightCount = 0, 0 + while leftCount < len(left) or rightCount < len(right): + if leftCount < len(left) and rightCount < len(right): + if left[leftCount] < right[rightCount]: + output.append(left[leftCount]) + leftCount += 1 + else: + output.append(right[rightCount]) + rightCount += 1 + if leftCount == len(left) and rightCount < right(right): + output.append(right[rightCount]) + rightCount += 1 + elif leftCount < len(left) and rightCount == len(right): + output.append(left[leftCount]) + leftCount += 1 + return output - def merge(self, left, right): - output = list() - leftCount, rightCount = 0, 0 - while leftCount < len(left) or rightCount < len(right): - if leftCount < len(left) and rightCount < len(right): - if left[leftCount] < right[rightCount]: - output.append(left[leftCount]) - leftCount += 1 - else: - output.append(right[rightCount]) - rightCount += 1 - if leftCount == len(left) and rightCount < right(right): - output.append(right[rightCount]) - rightCount += 1 - elif leftCount < len(left) and rightCount == len(right): - output.append(left[leftCount]) - leftCount += 1 - return output + def sort(self): + temp = self.mergeSort(self.lst) + self.lst = temp - def sort(self): - temp = self.mergeSort(self.lst) - self.lst = temp + def show(self): + return self.lst - def show(self): - return self.lst if __name__ == "__main__": - i = MergeSort([5,4,3,2,1]) - i.sort() - print i.show() + i = MergeSort([5, 4, 3, 2, 1]) + i.sort() + print(i.show()) diff --git a/Sorting/QuickSort/python/QuickSort.py b/Sorting/QuickSort/python/QuickSort.py index 2c3a6311..ea0b6800 100755 --- a/Sorting/QuickSort/python/QuickSort.py +++ b/Sorting/QuickSort/python/QuickSort.py @@ -8,26 +8,26 @@ def partition(self, left, right): for j in range(left, right): if self.lst[j] < pivot: - self.lst[i],self.lst[j] = self.lst[j],self.lst[i] + self.lst[i], self.lst[j] = self.lst[j], self.lst[i] i += 1 - self.lst[i],self.lst[right] = self.lst[right],self.lst[i] + self.lst[i], self.lst[right] = self.lst[right], self.lst[i] return i - + def sortHelper(self, left, right): if right > left: index = self.partition(left, right) - self.sortHelper(left, index-1) - self.sortHelper(index+1, right) + self.sortHelper(left, index - 1) + self.sortHelper(index + 1, right) def sort(self): - self.sortHelper(0, len(self.lst)-1) - + self.sortHelper(0, len(self.lst) - 1) def show(self): return self.lst + if __name__ == "__main__": - i = QuickSort([0,5,5,4,6,3,5,8,2,1]) + i = QuickSort([0, 5, 5, 4, 6, 3, 5, 8, 2, 1]) i.sort() - print i.show() + print(i.show()) diff --git a/Sorting/SelectionSort/python/SelectionSort.py b/Sorting/SelectionSort/python/SelectionSort.py index 8fb92883..1881c31c 100644 --- a/Sorting/SelectionSort/python/SelectionSort.py +++ b/Sorting/SelectionSort/python/SelectionSort.py @@ -1,4 +1,5 @@ -# Selection Sort: Find the minimum value at each pass and move it to the beginning +# Selection Sort: Find the minimum value at each pass and move it +# to the beginning def SelectionSort(arr): @@ -15,4 +16,4 @@ def SelectionSort(arr): if __name__ == "__main__": arr = [1, 5, 7, 2, 8, 3] - print SelectionSort(arr) # [1, 2, 3, 5, 7, 8] + print(SelectionSort(arr)) # [1, 2, 3, 5, 7, 8] diff --git a/Sorting/bubble sort/php/bubblesort.php b/Sorting/bubble sort/php/bubblesort.php index 65fe5d68..feec9549 100644 --- a/Sorting/bubble sort/php/bubblesort.php +++ b/Sorting/bubble sort/php/bubblesort.php @@ -1,18 +1,17 @@ - diff --git a/Sorting/bubble sort/python/BubbleSort.py b/Sorting/bubble sort/python/BubbleSort.py index 60c01df9..15cb9545 100644 --- a/Sorting/bubble sort/python/BubbleSort.py +++ b/Sorting/bubble sort/python/BubbleSort.py @@ -1,15 +1,16 @@ def bubbleSort(arr): - swap = True - while swap: - swap = False - for i in range(len(arr) - 1): - if arr[i] > arr[i + 1]: - x = arr[i] - arr[i] = arr[i + 1] - arr[i + 1] = x - swap = True - + swap = True + while swap: + swap = False + for i in range(len(arr) - 1): + if arr[i] > arr[i + 1]: + x = arr[i] + arr[i] = arr[i + 1] + arr[i + 1] = x + swap = True + + if __name__ == "__main__": - arr = [10, -43, 21, 0, 4, 67, 5, 3, 10] - bubbleSort(arr) - print(arr) + arr = [10, -43, 21, 0, 4, 67, 5, 3, 10] + bubbleSort(arr) + print(arr) diff --git a/String/Anagram/Group_Anagrams/group_anagram.py b/String/Anagram/Group_Anagrams/group_anagram.py index cb67e815..2a0a4502 100644 --- a/String/Anagram/Group_Anagrams/group_anagram.py +++ b/String/Anagram/Group_Anagrams/group_anagram.py @@ -15,8 +15,8 @@ for x in inp: arrPrint = [] for b in inp: - if(is_anagram.is_anagram(str(x), str(b))): - arrPrint.append(b) + if (is_anagram.is_anagram(str(x), str(b))): + arrPrint.append(b) arrFinal.append(arrPrint) i = i + 1 @@ -24,12 +24,10 @@ for i, j in enumerate(arrFinal[:-1]): try: compOne = j[0] - compTwo = arrFinal[i+1][0] - if(is_anagram.is_anagram(compOne, compTwo)): + compTwo = arrFinal[i + 1][0] + if (is_anagram.is_anagram(compOne, compTwo)): arrFinal.remove(j) - except: + except Exception: pass arrFinal.remove(arrFinal[0]) print(arrFinal) - - diff --git a/String/Anagram/Group_Anagrams/is_anagram.py b/String/Anagram/Group_Anagrams/is_anagram.py index 242d6afa..3431c8d0 100644 --- a/String/Anagram/Group_Anagrams/is_anagram.py +++ b/String/Anagram/Group_Anagrams/is_anagram.py @@ -1,20 +1,20 @@ def is_anagram(str1, str2): """Checks if two strings are anagrams of each other""" - #Get a count of all the characters in each string + # Get a count of all the characters in each string chars1 = get_alphabet(str1.lower()) chars2 = get_alphabet(str2.lower()) - #Check if both strings contain the same characters in the same amounts + # Check if both strings contain the same characters in the same amounts if chars1 == chars2: return True else: return False + def get_alphabet(string): """Creates a dictionary containing a count of the number of times each alphanumeric character in string is used.""" - """E.g. get_alphabet("Hello") would return {'H':1, 'e':1, 'l':2, 'o':1}""" alphabet = dict() for c in string: @@ -25,4 +25,3 @@ def get_alphabet(string): alphabet[c] = 1 return alphabet - diff --git a/String/Balanced Parentheses/balanced_parantheses.py b/String/Balanced Parentheses/balanced_parantheses.py index 0c8c7bcc..02a7ac05 100644 --- a/String/Balanced Parentheses/balanced_parantheses.py +++ b/String/Balanced Parentheses/balanced_parantheses.py @@ -1,5 +1,5 @@ -#A small check for balanced parantheses in Python 3 -#Added regex as a little extra +# A small check for balanced parantheses in Python 3 +# Added regex as a little extra import re @@ -7,31 +7,36 @@ opening_parantheses = ['[', '(', '{'] closing_parantheses = [']', ')', '}'] + def is_balanced(expr): - stack = [] - n = len(expr) - for i in range(0, n): - if(expr[i] in opening_parantheses): - stack.append(expr[i]) - elif(expr[i] in closing_parantheses): - matching_paranthesis = opening_parantheses[closing_parantheses.index(expr[i])] - if(stack.pop() != matching_paranthesis): - return False + stack = [] + n = len(expr) + for i in range(0, n): + if (expr[i] in opening_parantheses): + stack.append(expr[i]) + elif (expr[i] in closing_parantheses): + matching_paranthesis = opening_parantheses[closing_parantheses. + index(expr[i])] + if (stack.pop() != matching_paranthesis): + return False - return True if len(stack) == 0 else False + return True if len(stack) == 0 else False def main(): - expr = input("Please enter an expression with parantheses ('[','(','{','}',')',']') or 'test' for a fixed test: ") - if(expr == "test"): - expr = "({}[](([{()}])))" + expr = input( + "Please enter an expression with parantheses ('[','(','{','}',')',']') or 'test' for a fixed test: " + ) + if (expr == "test"): + expr = "({}[](([{()}])))" + + if (not any_parantheses.match(expr)): + print("No parantheses found!") + elif (is_balanced(expr)): + print("%s is balanced!" % expr) + else: + print("%s is not balanced!" % expr) - if(not any_parantheses.match(expr)): - print("No parantheses found!") - elif(is_balanced(expr)): - print("%s is balanced!" % expr) - else: - print("%s is not balanced!" % expr) if __name__ == '__main__': - main() + main() diff --git a/String/Hamming distance/hamming_distance.py b/String/Hamming distance/hamming_distance.py index 395eae35..a4cbbe72 100644 --- a/String/Hamming distance/hamming_distance.py +++ b/String/Hamming distance/hamming_distance.py @@ -1,14 +1,15 @@ -def hamming_distance(s1, s2): - """Returns the Hamming distance between two equal-length sequences""" - if len(s1) != len(s2): - raise ValueError("Sequences of unequal length") - return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) - -if __name__ == "__main__": - print hamming_distance("kittens", "kittens") # output is 0 - print hamming_distance("1011101 ", "1001001 ") # output is 2 - print hamming_distance("karolin", "kathrin") # output is 3 - try: - print hamming_distance("1011101", "100100") # throws exception - except ValueError as e: - print e \ No newline at end of file +def hamming_distance(s1, s2): + """Returns the Hamming distance between two equal-length sequences""" + if len(s1) != len(s2): + raise ValueError("Sequences of unequal length") + return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) + + +if __name__ == "__main__": + print(hamming_distance("kittens", "kittens")) # output is 0 + print(hamming_distance("1011101 ", "1001001 ")) # output is 2 + print(hamming_distance("karolin", "kathrin")) # output is 3 + try: + print(hamming_distance("1011101", "100100")) # throws exception + except ValueError as e: + print(e) diff --git a/String/Palindrome/is_palindrome.py b/String/Palindrome/is_palindrome.py index d52b8e52..fef8e013 100644 --- a/String/Palindrome/is_palindrome.py +++ b/String/Palindrome/is_palindrome.py @@ -1,17 +1,22 @@ -import re - -def is_palindrome(s): - """Checks if a given string is a palindrome.""" - if any(x.isupper() for x in s): - s = re.sub(r'[^\w]', '', s).lower() - if len(s) < 2: - return True - if s[0] != s[-1]: - return False - return is_palindrome(s[1:-1]) - -if __name__ == "__main__": - print is_palindrome("redivider") # output is True - print is_palindrome("123321") # output is True - print is_palindrome("palindrome") # output is False - print is_palindrome("On a clover, if alive, erupts a vast pure evil; a fire volcano") # output is True +import re + + +def is_palindrome(s): + """Checks if a given string is a palindrome.""" + if any(x.isupper() for x in s): + s = re.sub(r'[^\w]', '', s).lower() + if len(s) < 2: + return True + if s[0] != s[-1]: + return False + return is_palindrome(s[1:-1]) + + +if __name__ == "__main__": + print(is_palindrome("redivider")) # output is True + print(is_palindrome("123321")) # output is True + print(is_palindrome("palindrome")) # output is False + print( + is_palindrome( + "On a clover, if alive, erupts a vast pure evil; a fire volcano") + ) # output is True diff --git a/String/String Matching/rabin_karp_matcher.py b/String/String Matching/rabin_karp_matcher.py index f79b7919..c91a1c6d 100644 --- a/String/String Matching/rabin_karp_matcher.py +++ b/String/String Matching/rabin_karp_matcher.py @@ -28,24 +28,25 @@ def rabin_karp_matcher(T, P, d, q): p = 0 t = 0 # preprocessing - for i in range(m-1): - h = (h*d) % q + for i in range(m - 1): + h = (h * d) % q for i in range(m): - p = (d*p + ord(P[i])) % q - t = (d*t + ord(T[i])) % q + p = (d * p + ord(P[i])) % q + t = (d * t + ord(T[i])) % q # string matching - for s in range(n-m+1): + for s in range(n - m + 1): if p == t: for j in range(m): - if T[s+j] != P[j]: + if T[s + j] != P[j]: break j += 1 if j == m: print("Pattern found at index: " + str(s)) - if s < n-m: - t = (d*(t - ord(T[s])*h) + ord(T[s+m])) % q + if s < n - m: + t = (d * (t - ord(T[s]) * h) + ord(T[s + m])) % q if t < 0: # for negative t t += q - + + text = "JUSTANANOTHERTEXT" rabin_karp_matcher(text, "AN", len(text), 13) diff --git a/String/Top_K_Frequent_Words/top_k_frequent_words.py b/String/Top_K_Frequent_Words/top_k_frequent_words.py index 2061b734..62e63d0c 100644 --- a/String/Top_K_Frequent_Words/top_k_frequent_words.py +++ b/String/Top_K_Frequent_Words/top_k_frequent_words.py @@ -1,8 +1,13 @@ # Returns k number of words sorted on their occurrence def top_k_frequent_words(words, k: int): - return sorted(sorted(set(words)), key=lambda x: words.count(x), reverse=True)[:k] - + return sorted( + sorted(set(words)), key=lambda x: words.count(x), reverse=True)[:k] + + if __name__ == '__main__': - inpt = input('Enter space seperated words: ').split() - k = int(input('Enter the amount of words to retreive based on their occurance: ')) - print(top_k_frequent_words(inpt, k)) + inpt = input('Enter space seperated words: ').split() + k = int( + input( + 'Enter the amount of words to retreive based on their occurance: ') + ) + print(top_k_frequent_words(inpt, k))