Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. from collections import defaultdict
  2. import random
  3. from queue import Queue
  4.  
  5. connections = []
  6.  
  7. # GET INPUTS
  8. while True:
  9.     nodes = input()
  10.     if nodes == '':
  11.         break
  12.     connections.append(tuple([int(node) for node in sorted(nodes.split(','), key=int)]))
  13.  
  14.  
  15. # GENERATE GRAPH
  16. graph = defaultdict(list)
  17. for connection in connections:
  18.     n1, n2 = connection
  19.     if n1 not in graph[n2]:
  20.         graph[n2].append(n1)
  21.     if n2 not in graph[n1]:
  22.         graph[n1].append(n2)
  23.  
  24. new_connections = []
  25. explored = []
  26.  
  27. # TRAVERSE GRAPH
  28. while (len(graph) - len(explored)) > 0:
  29.     start_node = random.sample((set(list(graph)) - set(explored)), 1)[0]
  30.     queue = Queue()
  31.     queue.put((None, start_node))
  32.  
  33.     # Loop while there are nodes pending to be explored
  34.     while not queue.empty():
  35.         (previous_node, currently_exploring_node) = queue.get()
  36.         # If we have explored this node already, skip it
  37.         if currently_exploring_node in explored:
  38.             continue
  39.         # Append the connection to the new_connections list
  40.         if previous_node:
  41.             new_connections.append((previous_node, currently_exploring_node))
  42.         # Append current node to explored list
  43.         explored.append(currently_exploring_node)
  44.         # Get neighbours of current node
  45.         neighbouring_nodes = graph[currently_exploring_node]
  46.         # For all neighbours, enqueue those neighbours that have not been explored yet for exploration
  47.         for node in neighbouring_nodes:
  48.             if node not in explored:
  49.                 queue.put((currently_exploring_node, node))
  50.  
  51. print("Old Connections")
  52. print(connections)
  53. print("New Connections")
  54. print(new_connections)
  55. print("Number of edges that can be removed")
  56. print(len(connections) - len(new_connections))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement