def roadsAndLibraries(n, c_lib, c_road, cities): # Complete this function if not n: return 0 if c_lib <= c_road: return n * c_lib graph = Graph() # for _n in range(n): # graph.addVertex(Vertex(str(_n+1))) for edge in cities: try: graph.addVertex(Vertex(str(edge[0]))) except KeyError: pass try: graph.addVertex(Vertex(str(edge[1]))) except KeyError: pass graph.createEdge(str(edge[0]), str(edge[1])) print graph.degree subgraphs = graph.listSubGraphs() print subgraphs libraries = len(subgraphs) + (n - graph.degree) roads = 0 for g in subgraphs: roads += len(g) - 1 return (libraries * c_lib) + (roads * c_road)
from graphs import Graph, Vertex, Edge graph = Graph() for n in '123456': graph.addVertex(Vertex(n)) graph.createEdge('1', '2') graph.createEdge('1', '3') graph.createEdge('2', '3') graph.createEdge('2', '4') graph.createEdge('3', '4') graph.createEdge('5', '6') print graph.listSubGraphs()