Search code examples
pythongraph

Cannot insert a vertex in a graph


I'm trying to create a graph for a kind of social network analysis and I cannot use Networkx library (it is for an academic project). I have a csv file with data like this:

Column1, Column2
1563,133
171316,2
1563,924

I've created a method to read the content of the csv file and create the Vertex object of the graph:

def github_csv():
    data = []
    with open('Github1.csv', mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            follower = Vertex(row["follower"])
            followed = Vertex(row["followed"])
            data.append(Vertex(follower))
            data.append(Vertex(followed))
    return data

Then, I'm trying to insert the vertex on the graph with this:

def build_graph():
    graph_vertex = github_csv()
    graph = Graph(True)
    for vertex in graph_vertex:
        print(vertex)
        graph.insert_vertex(vertex)
    print(graph.vertex_count())
    return graph

My class Graph and insert_vertex method are:

class Graph:

    def __init__(self, directed=False):
        self._directed = directed
        self._number = 0           
        self._vertices = {} 
    
    def insert_vertex(self, x):
        v = Vertex(x)
        self._vertices[v] = {}    
        return v

    def vertex_count(self):
        return self._number

But, when I call build_graph(), the vertex count is equal to zero. What I'm doing wrong here? The output is something like:

36872
8135
5823
272950
797296
0
<__main__.Graph object at 0x00000234DD044F70>

Solution

  • You'll need to update value of _number , may be in insert_vertex as :

    def insert_vertex(self, x):
            v = Vertex(x)
            self._vertices[v] = {}   
            self._number = len(self._vertices)
            return v