Advertisement
STANAANDREY

graphs lsd

Nov 15th, 2022
703
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. from collections.abc import Set, Mapping
  2. from functools import reduce
  3.  
  4. graph = {
  5.     "a": {"b", "c"},
  6.     "b": set(),
  7.     "c": set()
  8. }
  9.  
  10.  
  11. def get_nodes(graph):
  12.     return list(graph.keys())
  13.  
  14.  
  15. def get_edges(graph: Mapping[Set]):
  16.     edges = set()
  17.  
  18.     def red_graph(acc, elem):
  19.         key, val = elem
  20.  
  21.         def red_node(acc2, elem2):
  22.             edges.add((key, elem2))
  23.  
  24.         reduce(red_node, val, None)
  25.  
  26.     reduce(red_graph, graph.items(), None)
  27.     return edges
  28.  
  29.  
  30. def add_node(graph: Mapping[Set], node):
  31.     if not node in graph:
  32.         graph[node] = set()
  33.     return graph
  34.  
  35.  
  36. def add_edge(graph: Mapping[Set], edge):
  37.     if edge[0] in graph:
  38.         graph[edge[0]].add(edge[1])
  39.     else:
  40.         graph[edge[0]] = {edge[1]}
  41.  
  42.     if not edge[1] in graph:
  43.         graph[edge[1]] = set()
  44.  
  45.     return graph
  46.  
  47.  
  48. # graph = add_node(graph, "ab")
  49. graph = add_edge(graph, ('b', 'c'))
  50. print(get_nodes(graph))
  51. print(get_edges(graph))
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement