根据给定的输入,我有一个类,该类的功能为图形添加了一条边。例如:如果输入为add James Larry 1
,则将在权重(亲密度级别)为James
的{{1}}和Larry
之间添加一条边。该图是集合的字典,因此,键是节点,值(集合)是边。
因此,此功能具有以下参数:源,目标和权重。该类如下所示:
1
我正在尝试实现以下代码:
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
文件的第一行是: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()
当我尝试运行此代码时,正在向我显示此错误:
回溯(最近通话最近一次):
文件
中的文件“ C:/.../ SocialGraph.py”,第24行grafo = main()
文件“ C:/.../ SocialGraph.py”在主行中的第20行
aGraph = DiGraph.DiGraph.addEdge(word [i] [1],word [i] [2],int(word [i] [3]))
addEdge中的文件“ C:... \ DiGraph.py”,第156行
eSet = self.graph.get(src)
AttributeError:'str'对象没有属性'graph'
该如何解决?
答案 0 :(得分:1)
DiGraph.DiGraph.addEdge(word[i][1],
您将此称为静态方法。 'word [i] [1]'变成'self'。
答案 1 :(得分:0)
您将addEdge
实现为实例方法,因此必须创建一个实例才能使用它。像这样:
# 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]))