From 9f5b26476738bfbeb68e4525d8bf9cd6d8000924 Mon Sep 17 00:00:00 2001 From: Srishtiops Date: Tue, 29 Oct 2024 20:58:14 +0530 Subject: [PATCH 1/3] Added codes related to graphs --- data_structures/graphs/BFS.py | 65 ++++++++++++++ data_structures/graphs/DFS.py | 57 ++++++++++++ data_structures/graphs/dijikstra_algorithm.py | 76 ++++++++++++++++ .../graphs/floyd_warshall_algorithm.py | 90 +++++++++++++++++++ 4 files changed, 288 insertions(+) create mode 100644 data_structures/graphs/BFS.py create mode 100644 data_structures/graphs/DFS.py create mode 100644 data_structures/graphs/dijikstra_algorithm.py create mode 100644 data_structures/graphs/floyd_warshall_algorithm.py diff --git a/data_structures/graphs/BFS.py b/data_structures/graphs/BFS.py new file mode 100644 index 000000000000..a2fde55c72e9 --- /dev/null +++ b/data_structures/graphs/BFS.py @@ -0,0 +1,65 @@ + + +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): + self.graph[u].append(v) + + # Function to print a BFS of graph + def BFS(self, s): + + # Mark all the vertices as not visited + visited = [False] * (max(self.graph) + 1) + + # Create a queue for BFS + queue = [] + + # Mark the source node as + # visited and enqueue it + queue.append(s) + visited[s] = True + + while queue: + + # Dequeue a vertex from + # queue and print it + s = queue.pop(0) + print(s, end=" ") + + # Get all adjacent vertices of the + # dequeued vertex s. + # If an adjacent has not been visited, + # then mark it visited and enqueue it + for i in self.graph[s]: + if not visited[i]: + queue.append(i) + visited[i] = True + +# Driver code +if __name__ == '__main__': + + # Create a graph given in + # the above diagram + g = Graph() + g.addEdge(0, 1) + g.addEdge(0, 2) + g.addEdge(1, 2) + g.addEdge(2, 0) + g.addEdge(2, 3) + g.addEdge(3, 3) + + print("Following is Breadth First Traversal" + " (starting from vertex 2)") + g.BFS(2) diff --git a/data_structures/graphs/DFS.py b/data_structures/graphs/DFS.py new file mode 100644 index 000000000000..7bd9742eda01 --- /dev/null +++ b/data_structures/graphs/DFS.py @@ -0,0 +1,57 @@ +from collections import defaultdict + +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): + self.graph[u].append(v) + + + # A function used by DFS + def DFSUtil(self, v, visited): + + # Mark the current node as visited + # and print it + visited.add(v) + print(v, end=' ') + + # Recur for all the vertices + # adjacent to this vertex + for neighbour in self.graph[v]: + if neighbour not in visited: + self.DFSUtil(neighbour, visited) + + + # The function to do DFS traversal. It uses + # recursive DFSUtil() + def DFS(self, v): + + # Create a set to store visited vertices + visited = set() + + # Call the recursive helper function + # to print DFS traversal + self.DFSUtil(v, visited) + + +# Driver's code +if __name__ == "__main__": + g = Graph() + g.addEdge(0, 1) + g.addEdge(0, 2) + g.addEdge(1, 2) + g.addEdge(2, 0) + g.addEdge(2, 3) + g.addEdge(3, 3) + + print("Following is Depth First Traversal (starting from vertex 2)") + + # Function call + g.DFS(2) \ No newline at end of file diff --git a/data_structures/graphs/dijikstra_algorithm.py b/data_structures/graphs/dijikstra_algorithm.py new file mode 100644 index 000000000000..846e65da9358 --- /dev/null +++ b/data_structures/graphs/dijikstra_algorithm.py @@ -0,0 +1,76 @@ +class Graph(): + + def __init__(self, vertices): + self.V = vertices + self.graph = [[0 for column in range(vertices)] + for row in range(vertices)] + + def printSolution(self, dist): + print("Vertex \t Distance from Source") + for node in range(self.V): + print(node, "\t\t", dist[node]) + + # A utility function to find the vertex with + # minimum distance value, from the set of vertices + # not yet included in shortest path tree + def minDistance(self, dist, sptSet): + + # Initialize minimum distance for next node + min = 1e7 + + # Search not nearest vertex not in the + # shortest path tree + for v in range(self.V): + if dist[v] < min and sptSet[v] == False: + min = dist[v] + min_index = v + + return min_index + + # Function that implements Dijkstra's single source + # shortest path algorithm for a graph represented + # using adjacency matrix representation + def dijkstra(self, src): + + dist = [1e7] * self.V + dist[src] = 0 + sptSet = [False] * self.V + + for cout in range(self.V): + + # Pick the minimum distance vertex from + # the set of vertices not yet processed. + # u is always equal to src in first iteration + u = self.minDistance(dist, sptSet) + + # Put the minimum distance vertex in the + # shortest path tree + sptSet[u] = True + + # Update dist value of the adjacent vertices + # of the picked vertex only if the current + # distance is greater than new distance and + # the vertex in not in the shortest path tree + for v in range(self.V): + if (self.graph[u][v] > 0 and + sptSet[v] == False and + dist[v] > dist[u] + self.graph[u][v]): + dist[v] = dist[u] + self.graph[u][v] + + self.printSolution(dist) + +# Driver program +g = Graph(9) +g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], + [4, 0, 8, 0, 0, 0, 0, 11, 0], + [0, 8, 0, 7, 0, 4, 0, 0, 2], + [0, 0, 7, 0, 9, 14, 0, 0, 0], + [0, 0, 0, 9, 0, 10, 0, 0, 0], + [0, 0, 4, 14, 10, 0, 2, 0, 0], + [0, 0, 0, 0, 0, 2, 0, 1, 6], + [8, 11, 0, 0, 0, 0, 1, 0, 7], + [0, 0, 2, 0, 0, 0, 6, 7, 0] + ] + +g.dijkstra(0) + diff --git a/data_structures/graphs/floyd_warshall_algorithm.py b/data_structures/graphs/floyd_warshall_algorithm.py new file mode 100644 index 000000000000..36459b88b55b --- /dev/null +++ b/data_structures/graphs/floyd_warshall_algorithm.py @@ -0,0 +1,90 @@ +V = 4 + +# Define infinity as the large +# enough value. This value will be +# used for vertices not connected to each other +INF = 99999 + +# Solves all pair shortest path +# via Floyd Warshall Algorithm + + +def floydWarshall(graph): + """ dist[][] will be the output + matrix that will finally + have the shortest distances + between every pair of vertices """ + """ initializing the solution matrix + same as input graph matrix + OR we can say that the initial + values of shortest distances + are based on shortest paths considering no + intermediate vertices """ + + dist = list(map(lambda i: list(map(lambda j: j, i)), graph)) + + """ Add all vertices one by one + to the set of intermediate + vertices. + ---> Before start of an iteration, + we have shortest distances + between all pairs of vertices + such that the shortest + distances consider only the + vertices in the set + {0, 1, 2, .. k-1} as intermediate vertices. + ----> After the end of a + iteration, vertex no. k is + added to the set of intermediate + vertices and the + set becomes {0, 1, 2, .. k} + """ + for k in range(V): + + # pick all vertices as source one by one + for i in range(V): + + # Pick all vertices as destination for the + # above picked source + for j in range(V): + + # If vertex k is on the shortest path from + # i to j, then update the value of dist[i][j] + dist[i][j] = min(dist[i][j], + dist[i][k] + dist[k][j] + ) + printSolution(dist) + + +# A utility function to print the solution +def printSolution(dist): + print("Following matrix shows the shortest distances\ + between every pair of vertices") + for i in range(V): + for j in range(V): + if(dist[i][j] == INF): + print("%7s" % ("INF"), end=" ") + else: + print("%7d\t" % (dist[i][j]), end=' ') + if j == V-1: + print() + + + +if __name__ == "__main__": + """ + 10 + (0)------->(3) + | /|\ + 5 | | + | | 1 + \|/ | + (1)------->(2) + 3 """ + graph = [[0, 5, INF, 10], + [INF, 0, 3, INF], + [INF, INF, 0, 1], + [INF, INF, INF, 0] + ] + # Function call + floydWarshall(graph) From e31c3014a429dd7c9d03021aeb37d0098ce6bc87 Mon Sep 17 00:00:00 2001 From: Srishtiops Date: Tue, 29 Oct 2024 23:48:24 +0530 Subject: [PATCH 2/3] Added patterns related code --- patterns/full_pyramid.py | 13 +++++++++++++ patterns/hollow_triangle_alphabet.py | 26 ++++++++++++++++++++++++++ patterns/hourglass_alphabet.py | 23 +++++++++++++++++++++++ patterns/left_triangle_alphabet.py | 13 +++++++++++++ patterns/pyramid_with_alphabet.py | 9 +++++++++ 5 files changed, 84 insertions(+) create mode 100644 patterns/full_pyramid.py create mode 100644 patterns/hollow_triangle_alphabet.py create mode 100644 patterns/hourglass_alphabet.py create mode 100644 patterns/left_triangle_alphabet.py create mode 100644 patterns/pyramid_with_alphabet.py diff --git a/patterns/full_pyramid.py b/patterns/full_pyramid.py new file mode 100644 index 000000000000..65cb79932165 --- /dev/null +++ b/patterns/full_pyramid.py @@ -0,0 +1,13 @@ +# Function to print full pyramid pattern +def full_pyramid(n): + for i in range(1, n + 1): + # Print leading spaces + for j in range(n - i): + print(" ", end="") + + # Print asterisks for the current row + for k in range(1, 2*i): + print("*", end="") + print() + +full_pyramid(5) diff --git a/patterns/hollow_triangle_alphabet.py b/patterns/hollow_triangle_alphabet.py new file mode 100644 index 000000000000..598b63f8bca1 --- /dev/null +++ b/patterns/hollow_triangle_alphabet.py @@ -0,0 +1,26 @@ +#define function +def hollow_left_triangle(rows): + + #change rows + for i in range(1, rows+1): + counter = 0 + for j in range(i): + # print characters at the end and start + if j == 0 or j == i-1: + print(chr(65 + counter), end='') + counter += 1 + else: + # print spaces in between + if i != rows: + print(' ', end='') + # print characters in the last row + else: + print(chr(65 + counter), end='') + counter += 1 + print() + +#rows to be spanned +n = 7 + +#call the function +hollow_left_triangle(n) diff --git a/patterns/hourglass_alphabet.py b/patterns/hourglass_alphabet.py new file mode 100644 index 000000000000..0ccc66e0ecef --- /dev/null +++ b/patterns/hourglass_alphabet.py @@ -0,0 +1,23 @@ +#define function +def print_hourglass(rows): + #print reverse pyramid + for i in range(rows - 1): + for j in range(i): + print(' ', end='') + for k in range(2 * (rows - i) - 1): + print(chr(65 + k), end='') + print() + + #print upright pyramid + for i in range(rows): + for j in range(rows - i - 1): + print(' ', end='') + for k in range(2 * i + 1): + print(chr(65 + k), end='') + print() + +#rows to be spanned +n = 7 + +#call the function +print_hourglass(n) diff --git a/patterns/left_triangle_alphabet.py b/patterns/left_triangle_alphabet.py new file mode 100644 index 000000000000..529e09948a54 --- /dev/null +++ b/patterns/left_triangle_alphabet.py @@ -0,0 +1,13 @@ +def left_triangle_pattern(rows): + # goes to new lines + for i in range(rows): + # print characters in the current line + for j in range(i + 1): + print(chr(j + 65), end="") + print() + +# number of rows to span +n = 7 + +# call the function +left_triangle_pattern(n) diff --git a/patterns/pyramid_with_alphabet.py b/patterns/pyramid_with_alphabet.py new file mode 100644 index 000000000000..ab2832b8351c --- /dev/null +++ b/patterns/pyramid_with_alphabet.py @@ -0,0 +1,9 @@ +n = 5 +alph = 65 +for i in range(0, n): + print(" " * (n-i), end=" ") + for j in range(0, i+1): + print(chr(alph), end=" ") + alph += 1 + alph = 65 + print() \ No newline at end of file From af078e48f9912bfe983cc1852e0c35fcd8b62518 Mon Sep 17 00:00:00 2001 From: Srishtiops Date: Thu, 31 Oct 2024 01:20:03 +0530 Subject: [PATCH 3/3] codes related to patterns --- data_structures/graphs/BFS.py | 65 -------------- data_structures/graphs/DFS.py | 57 ------------ data_structures/graphs/dijikstra_algorithm.py | 76 ---------------- .../graphs/floyd_warshall_algorithm.py | 90 ------------------- 4 files changed, 288 deletions(-) delete mode 100644 data_structures/graphs/BFS.py delete mode 100644 data_structures/graphs/DFS.py delete mode 100644 data_structures/graphs/dijikstra_algorithm.py delete mode 100644 data_structures/graphs/floyd_warshall_algorithm.py diff --git a/data_structures/graphs/BFS.py b/data_structures/graphs/BFS.py deleted file mode 100644 index a2fde55c72e9..000000000000 --- a/data_structures/graphs/BFS.py +++ /dev/null @@ -1,65 +0,0 @@ - - -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): - self.graph[u].append(v) - - # Function to print a BFS of graph - def BFS(self, s): - - # Mark all the vertices as not visited - visited = [False] * (max(self.graph) + 1) - - # Create a queue for BFS - queue = [] - - # Mark the source node as - # visited and enqueue it - queue.append(s) - visited[s] = True - - while queue: - - # Dequeue a vertex from - # queue and print it - s = queue.pop(0) - print(s, end=" ") - - # Get all adjacent vertices of the - # dequeued vertex s. - # If an adjacent has not been visited, - # then mark it visited and enqueue it - for i in self.graph[s]: - if not visited[i]: - queue.append(i) - visited[i] = True - -# Driver code -if __name__ == '__main__': - - # Create a graph given in - # the above diagram - g = Graph() - g.addEdge(0, 1) - g.addEdge(0, 2) - g.addEdge(1, 2) - g.addEdge(2, 0) - g.addEdge(2, 3) - g.addEdge(3, 3) - - print("Following is Breadth First Traversal" - " (starting from vertex 2)") - g.BFS(2) diff --git a/data_structures/graphs/DFS.py b/data_structures/graphs/DFS.py deleted file mode 100644 index 7bd9742eda01..000000000000 --- a/data_structures/graphs/DFS.py +++ /dev/null @@ -1,57 +0,0 @@ -from collections import defaultdict - -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): - self.graph[u].append(v) - - - # A function used by DFS - def DFSUtil(self, v, visited): - - # Mark the current node as visited - # and print it - visited.add(v) - print(v, end=' ') - - # Recur for all the vertices - # adjacent to this vertex - for neighbour in self.graph[v]: - if neighbour not in visited: - self.DFSUtil(neighbour, visited) - - - # The function to do DFS traversal. It uses - # recursive DFSUtil() - def DFS(self, v): - - # Create a set to store visited vertices - visited = set() - - # Call the recursive helper function - # to print DFS traversal - self.DFSUtil(v, visited) - - -# Driver's code -if __name__ == "__main__": - g = Graph() - g.addEdge(0, 1) - g.addEdge(0, 2) - g.addEdge(1, 2) - g.addEdge(2, 0) - g.addEdge(2, 3) - g.addEdge(3, 3) - - print("Following is Depth First Traversal (starting from vertex 2)") - - # Function call - g.DFS(2) \ No newline at end of file diff --git a/data_structures/graphs/dijikstra_algorithm.py b/data_structures/graphs/dijikstra_algorithm.py deleted file mode 100644 index 846e65da9358..000000000000 --- a/data_structures/graphs/dijikstra_algorithm.py +++ /dev/null @@ -1,76 +0,0 @@ -class Graph(): - - def __init__(self, vertices): - self.V = vertices - self.graph = [[0 for column in range(vertices)] - for row in range(vertices)] - - def printSolution(self, dist): - print("Vertex \t Distance from Source") - for node in range(self.V): - print(node, "\t\t", dist[node]) - - # A utility function to find the vertex with - # minimum distance value, from the set of vertices - # not yet included in shortest path tree - def minDistance(self, dist, sptSet): - - # Initialize minimum distance for next node - min = 1e7 - - # Search not nearest vertex not in the - # shortest path tree - for v in range(self.V): - if dist[v] < min and sptSet[v] == False: - min = dist[v] - min_index = v - - return min_index - - # Function that implements Dijkstra's single source - # shortest path algorithm for a graph represented - # using adjacency matrix representation - def dijkstra(self, src): - - dist = [1e7] * self.V - dist[src] = 0 - sptSet = [False] * self.V - - for cout in range(self.V): - - # Pick the minimum distance vertex from - # the set of vertices not yet processed. - # u is always equal to src in first iteration - u = self.minDistance(dist, sptSet) - - # Put the minimum distance vertex in the - # shortest path tree - sptSet[u] = True - - # Update dist value of the adjacent vertices - # of the picked vertex only if the current - # distance is greater than new distance and - # the vertex in not in the shortest path tree - for v in range(self.V): - if (self.graph[u][v] > 0 and - sptSet[v] == False and - dist[v] > dist[u] + self.graph[u][v]): - dist[v] = dist[u] + self.graph[u][v] - - self.printSolution(dist) - -# Driver program -g = Graph(9) -g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], - [4, 0, 8, 0, 0, 0, 0, 11, 0], - [0, 8, 0, 7, 0, 4, 0, 0, 2], - [0, 0, 7, 0, 9, 14, 0, 0, 0], - [0, 0, 0, 9, 0, 10, 0, 0, 0], - [0, 0, 4, 14, 10, 0, 2, 0, 0], - [0, 0, 0, 0, 0, 2, 0, 1, 6], - [8, 11, 0, 0, 0, 0, 1, 0, 7], - [0, 0, 2, 0, 0, 0, 6, 7, 0] - ] - -g.dijkstra(0) - diff --git a/data_structures/graphs/floyd_warshall_algorithm.py b/data_structures/graphs/floyd_warshall_algorithm.py deleted file mode 100644 index 36459b88b55b..000000000000 --- a/data_structures/graphs/floyd_warshall_algorithm.py +++ /dev/null @@ -1,90 +0,0 @@ -V = 4 - -# Define infinity as the large -# enough value. This value will be -# used for vertices not connected to each other -INF = 99999 - -# Solves all pair shortest path -# via Floyd Warshall Algorithm - - -def floydWarshall(graph): - """ dist[][] will be the output - matrix that will finally - have the shortest distances - between every pair of vertices """ - """ initializing the solution matrix - same as input graph matrix - OR we can say that the initial - values of shortest distances - are based on shortest paths considering no - intermediate vertices """ - - dist = list(map(lambda i: list(map(lambda j: j, i)), graph)) - - """ Add all vertices one by one - to the set of intermediate - vertices. - ---> Before start of an iteration, - we have shortest distances - between all pairs of vertices - such that the shortest - distances consider only the - vertices in the set - {0, 1, 2, .. k-1} as intermediate vertices. - ----> After the end of a - iteration, vertex no. k is - added to the set of intermediate - vertices and the - set becomes {0, 1, 2, .. k} - """ - for k in range(V): - - # pick all vertices as source one by one - for i in range(V): - - # Pick all vertices as destination for the - # above picked source - for j in range(V): - - # If vertex k is on the shortest path from - # i to j, then update the value of dist[i][j] - dist[i][j] = min(dist[i][j], - dist[i][k] + dist[k][j] - ) - printSolution(dist) - - -# A utility function to print the solution -def printSolution(dist): - print("Following matrix shows the shortest distances\ - between every pair of vertices") - for i in range(V): - for j in range(V): - if(dist[i][j] == INF): - print("%7s" % ("INF"), end=" ") - else: - print("%7d\t" % (dist[i][j]), end=' ') - if j == V-1: - print() - - - -if __name__ == "__main__": - """ - 10 - (0)------->(3) - | /|\ - 5 | | - | | 1 - \|/ | - (1)------->(2) - 3 """ - graph = [[0, 5, INF, 10], - [INF, 0, 3, INF], - [INF, INF, 0, 1], - [INF, INF, INF, 0] - ] - # Function call - floydWarshall(graph)