Reputation: 23
I have a class with a function that adds an edge to the graph, according to the input given. For example: if the input is add James Larry 1
, an edge will be added between James
and Larry
with the weight (intimacy level) 1
. The graph is a dictionary of sets, so, the keys are the node and the values (sets) are the edges.
So, this function has as parameters: the source, the destination and the weight. The class is represented below:
class DiGraph(object):
# Create an empty graph.
def __init__(self):
## A dictionary that stores an entry of a node, as the key, and a set of outgoing edges
# (destination node, weight) from the node, as its value.
self.graph = {}
## Total number of edges in the graph.
self.__numEdges = 0
## The largest edge distance.
# self.__infinity = sys.maxint
self.__infinity = sys.maxsize
## Holds the path from a source node to a given node.
self.__pathToNode = None
## Accumulated distance from source to a node.
self.__dist = None
### (...)
def addEdge(self, src, dst, c=1):
if ( src == None or dst == None or c <= 0 or src == dst ):
return False
# the edge set of src
eSet = self.graph.get(src)
e = Edge(dst,c) # new edge
if eSet == None:
# no edge starting at src, so create a new edge set
eSet = set()
self.__numEdges += 1
else:
ed = self.getEdge(src,dst)
if ( ed != None ):
ed.setCost(c)
return True
else:
self.__numEdges += 1
eSet.add(e) # a set does not have duplicates
self.graph[src] = eSet
if not self.hasVertex(dst):
self.addVertex(dst)
return True
I am trying to implement this code:
import DiGraph
#Create an empty graph
def main():
aGraph = {}
f = open("infile.txt")
contents = f.read()
lines = contents.splitlines()
word = []
for line in lines:
word.append(line.split())
for i in range(len(word)):
if word[i][0] == 'add':
aGraph = DiGraph.DiGraph.addEdge(word[i][1], word[i][2], int(word[i][3]))
return aGraph
grafo = main()
And the first line of the file is: add James Larry 1
This error is being showed to me when I try to run this code:
Traceback (most recent call last):
File "C:/.../SocialGraph.py", line 24, in
grafo = main()
File "C:/.../SocialGraph.py", line 20, in main
aGraph = DiGraph.DiGraph.addEdge(word[i][1], word[i][2], int(word[i][3]))
File "C:...\DiGraph.py", line 156, in addEdge
eSet = self.graph.get(src)
AttributeError: 'str' object has no attribute 'graph'
What can I do to correct this?
Upvotes: 0
Views: 558
Reputation: 3378
You implement addEdge
as an instance method so that you have to create an instance to use it. Like so:
# create DiGraph instance
diGraph = DiGraph.DiGraph()
for i in range(len(word)):
if word[i][0] == 'add':
aGraph = diGraph.addEdge(word[i][1], word[i][2], int(word[i][3]))
Upvotes: 0
Reputation: 286
DiGraph.DiGraph.addEdge(word[i][1],
You call this as a static method. 'word[i][1]' becomes 'self'.
Upvotes: 1