同步操作将从 编程语言算法集/Python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
from collections import dequedef _input(message):return input(message).strip().split(" ")def initialize_unweighted_directed_graph(node_count: int, edge_count: int) -> dict[int, list[int]]:graph: dict[int, list[int]] = {}for i in range(node_count):graph[i + 1] = []for e in range(edge_count):x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> "))graph[x].append(y)return graphdef initialize_unweighted_undirected_graph(node_count: int, edge_count: int) -> dict[int, list[int]]:graph: dict[int, list[int]] = {}for i in range(node_count):graph[i + 1] = []for e in range(edge_count):x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> "))graph[x].append(y)graph[y].append(x)return graphdef initialize_weighted_undirected_graph(node_count: int, edge_count: int) -> dict[int, list[tuple[int, int]]]:graph: dict[int, list[tuple[int, int]]] = {}for i in range(node_count):graph[i + 1] = []for e in range(edge_count):x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> "))graph[x].append((y, w))graph[y].append((x, w))return graphif __name__ == "__main__":n, m = (int(i) for i in _input("Number of nodes and edges: "))graph_choice = int(_input("Press 1 or 2 or 3 \n""1. Unweighted directed \n""2. Unweighted undirected \n""3. Weighted undirected \n")[0])g = {1: initialize_unweighted_directed_graph,2: initialize_unweighted_undirected_graph,3: initialize_weighted_undirected_graph,}[graph_choice](n, m)"""--------------------------------------------------------------------------------Depth First Search.Args : G - Dictionary of edgess - Starting NodeVars : vis - Set of visited nodesS - Traversal Stack--------------------------------------------------------------------------------"""def dfs(g, s):""">>> dfs({1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}, 1)12453"""vis, _s = {s}, [s]print(s)while _s:flag = 0for i in g[_s[-1]]:if i not in vis:_s.append(i)vis.add(i)flag = 1print(i)breakif not flag:_s.pop()"""--------------------------------------------------------------------------------Breadth First Search.Args : G - Dictionary of edgess - Starting NodeVars : vis - Set of visited nodesQ - Traversal Stack--------------------------------------------------------------------------------"""def bfs(g, s):""">>> bfs({1: [2, 3], 2: [4, 5], 3: [6, 7], 4: [], 5: [8], 6: [], 7: [], 8: []}, 1)12345678"""vis, q = {s}, deque([s])print(s)while q:u = q.popleft()for v in g[u]:if v not in vis:vis.add(v)q.append(v)print(v)"""--------------------------------------------------------------------------------Dijkstra's shortest path AlgorithmArgs : G - Dictionary of edgess - Starting NodeVars : dist - Dictionary storing shortest distance from s to every other nodeknown - Set of knows nodespath - Preceding node in path--------------------------------------------------------------------------------"""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)79112020"""dist, known, path = {s: 0}, set(), {s: 0}while True:if len(known) == len(g) - 1:breakmini = 100000for key, value in dist:if key not in known and value < mini:mini = valueu = keyknown.add(u)for v in g[u]:if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000):dist[v[0]] = dist[u] + v[1]path[v[0]] = ufor key, value in dist.items():if key != s:print(value)"""--------------------------------------------------------------------------------Topological Sort--------------------------------------------------------------------------------"""def topo(g, ind=None, q=None):if q is None:q = [1]if ind is None:ind = [0] * (len(g) + 1) # SInce oth Index is ignoredfor u in g:for v in g[u]:ind[v] += 1q = deque()for i in g:if ind[i] == 0:q.append(i)if len(q) == 0:returnv = q.popleft()print(v)for w in g[v]:ind[w] -= 1if ind[w] == 0:q.append(w)topo(g, ind, q)"""--------------------------------------------------------------------------------Reading an Adjacency matrix--------------------------------------------------------------------------------"""def adjm():r"""Reading an Adjacency matrixParameters:NoneReturns:tuple: A tuple containing a list of edges and number of edgesExample:>>> # Simulate user input for 3 nodes>>> input_data = "4\n0 1 0 1\n1 0 1 0\n0 1 0 1\n1 0 1 0\n">>> import sys,io>>> original_input = sys.stdin>>> sys.stdin = io.StringIO(input_data) # Redirect stdin for testing>>> adjm()([(0, 1, 0, 1), (1, 0, 1, 0), (0, 1, 0, 1), (1, 0, 1, 0)], 4)>>> sys.stdin = original_input # Restore original stdin"""n = int(input().strip())a = []for _ in range(n):a.append(tuple(map(int, input().strip().split())))return a, n"""--------------------------------------------------------------------------------Floyd Warshall's algorithmArgs : G - Dictionary of edgess - Starting NodeVars : dist - Dictionary storing shortest distance from s to every other nodeknown - Set of knows nodespath - Preceding node in path--------------------------------------------------------------------------------"""def floy(a_and_n):(a, n) = a_and_ndist = list(a)path = [[0] * n for i in range(n)]for k in range(n):for i in range(n):for j in range(n):if dist[i][j] > dist[i][k] + dist[k][j]:dist[i][j] = dist[i][k] + dist[k][j]path[i][k] = kprint(dist)"""--------------------------------------------------------------------------------Prim's MST AlgorithmArgs : G - Dictionary of edgess - Starting NodeVars : dist - Dictionary storing shortest distance from s to nearest nodeknown - Set of knows nodespath - Preceding node in path--------------------------------------------------------------------------------"""def prim(g, s):dist, known, path = {s: 0}, set(), {s: 0}while True:if len(known) == len(g) - 1:breakmini = 100000for key, value in dist.items():if key not in known and value < mini:mini = valueu = keyknown.add(u)for v in g[u]:if v[0] not in known and v[1] < dist.get(v[0], 100000):dist[v[0]] = v[1]path[v[0]] = ureturn dist"""--------------------------------------------------------------------------------Accepting Edge listVars : n - Number of nodesm - Number of edgesReturns : l - Edge listn - Number of Nodes--------------------------------------------------------------------------------"""def edglist():r"""Get the edges and number of edges from the userParameters:NoneReturns:tuple: A tuple containing a list of edges and number of edgesExample:>>> # Simulate user input for 3 edges and 4 vertices: (1, 2), (2, 3), (3, 4)>>> input_data = "4 3\n1 2\n2 3\n3 4\n">>> import sys,io>>> original_input = sys.stdin>>> sys.stdin = io.StringIO(input_data) # Redirect stdin for testing>>> edglist()([(1, 2), (2, 3), (3, 4)], 4)>>> sys.stdin = original_input # Restore original stdin"""n, m = tuple(map(int, input().split(" ")))edges = []for _ in range(m):edges.append(tuple(map(int, input().split(" "))))return edges, n"""--------------------------------------------------------------------------------Kruskal's MST AlgorithmArgs : E - Edge listn - Number of NodesVars : s - Set of all nodes as unique disjoint sets (initially)--------------------------------------------------------------------------------"""def krusk(e_and_n):"""Sort edges on the basis of distance"""(e, n) = e_and_ne.sort(reverse=True, key=lambda x: x[2])s = [{i} for i in range(1, n + 1)]while True:if len(s) == 1:breakprint(s)x = e.pop()for i in range(len(s)):if x[0] in s[i]:breakfor j in range(len(s)):if x[1] in s[j]:if i == j:breaks[j].update(s[i])s.pop(i)breakdef find_isolated_nodes(graph):"""Find the isolated node in the graphParameters:graph (dict): A dictionary representing a graph.Returns:list: A list of isolated nodes.Examples:>>> graph1 = {1: [2, 3], 2: [1, 3], 3: [1, 2], 4: []}>>> find_isolated_nodes(graph1)[4]>>> graph2 = {'A': ['B', 'C'], 'B': ['A'], 'C': ['A'], 'D': []}>>> find_isolated_nodes(graph2)['D']>>> graph3 = {'X': [], 'Y': [], 'Z': []}>>> find_isolated_nodes(graph3)['X', 'Y', 'Z']>>> graph4 = {1: [2, 3], 2: [1, 3], 3: [1, 2]}>>> find_isolated_nodes(graph4)[]>>> graph5 = {}>>> find_isolated_nodes(graph5)[]"""isolated = []for node in graph:if not graph[node]:isolated.append(node)return isolated
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。