0

I wrote this class about a graph in which it takes a list v for the name of dots and a tuple e for which dots are connected through a line. now I want to know which dots I can get from one to another through these lines. for example in : G = Graph(["A" , "B" , "C" , "X" , "Z"] , {('A' , 'B') ,('A' ,'C') , ('X' , 'Z')}) B and C are connected through lines , not directly but you can get from one to another using lines. if you go from B to A then from A to C. But you can't do that with X and A.

The idea is that I wrote a function neighbours that find out which dots are directly connected through lines :

    def neighbours(self,i):
    n = ""
    for x in self.e :
        if x[1] == i :
            n =  x[0]
        if x[0] == i :
            n = n + x[1]
    return n

and I would do some form of recursive function that finds out if they have common "neighbours" then if their neighbours have common neighbours ....

Polat
  • 57
  • 4

1 Answers1

0

You're basically trying to find which are the connected components of a graph. You can use Networkx to easily do this:

from networkx import Graph
from networkx.algorithms.components import connected_components

G = Graph()
G.add_nodes_from(['A', 'B', 'C', 'X', 'Z'])
G.add_edges_from([('A', 'B'), ('A', 'C'), ('X', 'Z')])

print(list(connected_components(G)))

Here is the result that is printed by the code above:

[{'C', 'A', 'B'}, {'X', 'Z'}]
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
  • Not allowed to use that module . is there anyone to do it through a recursive function ? – Polat Jan 31 '22 at 13:17