Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import defaultdict
- import random
- from queue import Queue
- connections = []
- # GET INPUTS
- while True:
- nodes = input()
- if nodes == '':
- break
- connections.append(tuple([int(node) for node in sorted(nodes.split(','), key=int)]))
- # GENERATE GRAPH
- graph = defaultdict(list)
- for connection in connections:
- n1, n2 = connection
- if n1 not in graph[n2]:
- graph[n2].append(n1)
- if n2 not in graph[n1]:
- graph[n1].append(n2)
- new_connections = []
- explored = []
- # TRAVERSE GRAPH
- while (len(graph) - len(explored)) > 0:
- start_node = random.sample((set(list(graph)) - set(explored)), 1)[0]
- queue = Queue()
- queue.put((None, start_node))
- # Loop while there are nodes pending to be explored
- while not queue.empty():
- (previous_node, currently_exploring_node) = queue.get()
- # If we have explored this node already, skip it
- if currently_exploring_node in explored:
- continue
- # Append the connection to the new_connections list
- if previous_node:
- new_connections.append((previous_node, currently_exploring_node))
- # Append current node to explored list
- explored.append(currently_exploring_node)
- # Get neighbours of current node
- neighbouring_nodes = graph[currently_exploring_node]
- # For all neighbours, enqueue those neighbours that have not been explored yet for exploration
- for node in neighbouring_nodes:
- if node not in explored:
- queue.put((currently_exploring_node, node))
- print("Old Connections")
- print(connections)
- print("New Connections")
- print(new_connections)
- print("Number of edges that can be removed")
- print(len(connections) - len(new_connections))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement