I'm writing a function get_connected_components
for a class Graph
:
def get_connected_components(self):
path=[]
for i in self.graph.keys():
q=self.graph[i]
while q:
print(q)
v=q.pop(0)
if not v in path:
path=path+[v]
return path
My graph is:
{0: [(0, 1), (0, 2), (0, 3)], 1: [], 2: [(2, 1)], 3: [(3, 4), (3, 5)], \
4: [(4, 3), (4, 5)], 5: [(5, 3), (5, 4), (5, 7)], 6: [(6, 8)], 7: [], \
8: [(8, 9)], 9: []}
where the keys are the nodes and the values are the edge. My function gives me this connected component:
[(0, 1), (0, 2), (0, 3), (2, 1), (3, 4), (3, 5), (4, 3), (4, 5), (5, 3), \
(5, 4), (5, 7), (6, 8), (8, 9)]
But I would have two different connected components, like:
[[(0, 1), (0, 2), (0, 3), (2, 1), (3, 4), (3, 5), (4, 3), (4, 5), \
(5, 3), (5, 4), (5, 7)],[(6, 8), (8, 9)]]
I don't understand where I made the mistake. Can anyone help me?
3: [(3, 4), (3, 5)]
. We already know that the edge is starting from 3! – Conoscentifor i in self.graph.keys(): q=self.graph[i]
you canfor (i, q) in self.graph.iteritems()
– Packsaddlepath
is with the statementpath = path + [v]
, which adds an edge to the list. If you want to create a list of lists of edges, then you need to have code that can make more than one list of edges, and add them to the list of list of edges... – Lissa