我是Python的新手,我想制作Dijkstra的算法,而且我一开始就遇到问题。
我有顶点和边的对象:
class Vertex:
minDistance = float('inf')
previousVertex = None
edges = []
id = None
name = None
def __init__(self, id, name):
self.id = id
self.name = name
class Edge:
source = None
target = None
weight = None
def __init__(self, source, target, weight):
self.source = source
self.target = target
self.weight = weight
我想要一个顶点和他的属性 edge 添加从其开始的每个边缘。为我拥有的每个顶点执行此操作:
vertices = []
def createGraph(self, vertices, edgesToVertices):
self.vertices = vertices[:]
for x in vertices:
for edge in edgesToVertices:
if edge.source is x.id:
x.edges.append(edge)
问题是当我追加到最后一行时,边缘被添加到列表中的所有顶点。 有人可以解释一下我做错了什么以及为什么?
答案 0 :(得分:1)
您在edges
中定义的列表Vertex
是一个类变量。因此,如果您修改它,它会影响所有Vertex
个实例(因此您正在描述的行为)。
你能做的是:
class Vertex:
def __init__(self, id, name):
self.id = id
self.name = name
self.edges = []
self.previousVertex = None
self.minDistance = float('inf')
class Edge:
def __init__(self, source, target, weight):
self.source = source
self.target = target
self.weight = weight
这样,edges
属于每个实例。
顺便说一下,我猜你打算createGraph()
加入Edge
。如果是这种情况,您可以像下面这样实现它:
class Edge:
def __init__(self, source, target, weight):
self.source = source
self.target = target
self.weight = weight
def createGraph(self, vertices, edgesToVertices):
for vertex in vertices:
for edge in edgesToVertices:
if edge.source is vertex.id:
vertex.edges.append(edge)