I'm new in Python and I want to make Dijkstra's algorithm and I'm having problem in the very beginning.
I have objects for vertices and edges:
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
I want to take a vertex and to his property edges add every edge that starts in it. Do this for every vertex I have:
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)
The problem is when I append the on the last line, the edge is added to ALL vertices in the list. Can someone please explain what am I doing wrong and why?
The list,
edges
, that you defined inVertex
is a class variable. So, if you modify it, it affects allVertex
instances (hence the behavior that you're describing).What you can do is:
This way,
edges
belongs to each instance.By the way, I'm guessing that you intend
createGraph()
to be part ofEdge
. If that were the case, you could implement it like the following: