我必须使用Adjacency List或Matrix创建图形,并包含添加Vertex和Edge的函数。然而,我在同一行中不断得到不同的错误。 我在
中收到此错误def getConnection(self):
return self.Edge[()]
这就是我所得到的就是这样。我试过了
return self.Edge()
和
return self.Edge[]
但我发现其他类型的错误。我需要在这里更改什么?
#Graph for Reference and use in BFS and DFS
graph = {'0': ['2'],
'1': ['3', '0'],
'2': ['3', '4'],
'3': ['2', '4', '5'],
'4': ['5', '6'],
'5': ['6', '7'],
'6': ['7', '8'],
'7': ['8', '9'],
'8': ['9', '0'],
'9': ['0', '5'] }
class Vertex:
def __init__(self, Label, Edge):
self.Label = 0
self.Edge = []
def AddNeighbour(self, neighbour, weight=0):
self.Connection[neighbour] = weight
def __str__(self):
return str(self.Label) + ' connected to: ' + str([i.Label for i in self.Edge])
def getConnection(self):
return self.Edge[()]
def getLabel(self):
return self.Label
class Graph:
def __init__(self):
self.VertexList = {}
self.NumVertices = 0
def AddVertex(self, Label):
self.NumVertices = self.NumVertices + 1
NewVertex = Vertex(Label, None)
self.VertexList[Label] = NewVertex
return NewVertex
def GetVertex(self,n):
if n in self.VertexList:
return self.VertexList[n]
else:
return None
def __contains__(self,n):
return n in self.VertexList
def AddNeighbour(self, neighbour, weight=0):
self.Connection[neighbour] = weight
def AddEdge(self,f,t,cost=0):
if f not in self.VertexList:
NewVertex = self.AddVertex(f)
if t not in self.VertexList:
NewVertex = self.AddVertex(t)
def GetVertices(self):
return self.VertexList.Label()
def __iter__(self):
return iter(self.VertexList.values())
g = Graph()
for i in range(10):
g.AddVertex(i)
g.VertexList
g.AddEdge(0,2,0)
g.AddEdge(0,3,0)
g.AddEdge(1,3,0)
g.AddEdge(1,0,0)
g.AddEdge(2,3,0)
g.AddEdge(2,4,0)
g.AddEdge(3,2,0)
g.AddEdge(3,4,0)
g.AddEdge(3,5,0)
g.AddEdge(4,5,0)
g.AddEdge(4,6,0)
g.AddEdge(5,6,0)
g.AddEdge(5,7,0)
g.AddEdge(6,7,0)
g.AddEdge(6,8,0)
g.AddEdge(7,8,0)
g.AddEdge(7,9,0)
g.AddEdge(8,9,0)
g.AddEdge(8,0,0)
g.AddEdge(9,0,0)
g.AddEdge(9,5,0)
for v in g:
for w in v.getConnection():
print("( %s , %s )" % (v.getLabel(), w.getLabel()))
答案 0 :(得分:0)
由于您将Edge定义为列表,因此可以返回:
return self.Edge
return self.Edge[:]
return self.Edge[i]
return self.Edge[i:j]
当然,在最后两种情况下,您必须分别定义和初始化i和j。如果不使用,它们将分别表示列表的开头和结尾(即self.Egde[:j]
将返回到列表j的所有元素的列表。关于该主题可能有许多变化:最后一个元素,两个元素,......