From 2daf7c3dc668b4b3c829cd4252c177810bb46ce0 Mon Sep 17 00:00:00 2001 From: Scarfinos Date: Wed, 6 Nov 2024 16:17:58 +0100 Subject: [PATCH] #9943 : Adding coverage test for basic_graphs.py --- graphs/basic_graphs.py | 56 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/graphs/basic_graphs.py b/graphs/basic_graphs.py index 25c8045b3..73861a01a 100644 --- a/graphs/basic_graphs.py +++ b/graphs/basic_graphs.py @@ -8,6 +8,15 @@ def _input(message): def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: + """ + Example: + Edge 1: 1 2 + Edge 2: 3 2 + Edge 3: 2 4 + >>> import io, sys ; sys.stdin = io.StringIO(chr(10).join(['1 2','3 2', '2 4'])) # input + >>> initialize_unweighted_directed_graph(4, 3) + Edge 1: Edge 2: Edge 3: {1: [2], 2: [4], 3: [2], 4: []} + """ graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] @@ -21,6 +30,15 @@ def initialize_unweighted_directed_graph( def initialize_unweighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: + """ + Example: + Edge 1: 1 2 + Edge 2: 3 2 + Edge 3: 2 4 + >>> import io, sys ; sys.stdin = io.StringIO(chr(10).join(['1 2','3 2', '2 4'])) # input + >>> initialize_unweighted_undirected_graph(4, 3) + Edge 1: Edge 2: Edge 3: {1: [2], 2: [1, 3, 4], 3: [2], 4: [2]} + """ graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] @@ -35,6 +53,17 @@ def initialize_unweighted_undirected_graph( def initialize_weighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[tuple[int, int]]]: + """ + Example: + Edge 1: 1 2 1 + Edge 2: 3 2 6 + Edge 3: 2 4 10 + Edge 4: 4 1 7 + Edge 5: 4 3 12 + >>> import io, sys ; sys.stdin = io.StringIO(chr(10).join(['1 2 1','3 2 6', '2 4 10', '4 1 7', '4 3 12'])) # input + >>> initialize_weighted_undirected_graph(4, 5) + Edge 1: Edge 2: Edge 3: Edge 4: Edge 5: {1: [(2, 1), (4, 7)], 2: [(1, 1), (3, 6), (4, 10)], 3: [(2, 6), (4, 12)], 4: [(2, 10), (1, 7), (3, 12)]} + """ graph: dict[int, list[tuple[int, int]]] = {} for i in range(node_count): graph[i + 1] = [] @@ -77,6 +106,14 @@ if __name__ == "__main__": def dfs(g, s): + """ + >>> dfs({1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}, 1) + 1 + 2 + 4 + 5 + 3 + """ vis, _s = {s}, [s] print(s) while _s: @@ -104,6 +141,17 @@ def dfs(g, s): def bfs(g, s): + """ + >>> bfs({1: [2, 3], 2: [4, 5], 3: [6, 7], 4: [], 5: [8], 6: [], 7: [], 8: []}, 1) + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + """ vis, q = {s}, deque([s]) print(s) while q: @@ -128,6 +176,14 @@ def bfs(g, s): def dijk(g, s): + """ + dijk({1: [(2, 7), (3, 9), (6, 14)], 2: [(1, 7), (3, 10), (4, 15)], 3: [(1, 9), (2, 10), (4, 11), (6, 2)], 4: [(2, 15), (3, 11), (5, 6)], 5: [(4, 6), (6, 9)], 6: [(1, 14), (3, 2), (5, 9)]}, 1) + 7 + 9 + 11 + 20 + 20 + """ dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: