eba340
eba340

Reputation: 19

Unintended connections between vertices in graph

So I'm doing some practice with graph theory and have this simple vertex class:

class Vertex:
    def __init__(self, value, connections={}):
        self.value = value
        self.connections = connections

    def add_connection(self, vertex, weight=1):
        self.connections[vertex] = weight

I then create a number of vertices like so:

a = Vertex(1)
b = Vertex(2)
c = Vertex(3)
d = Vertex(4)

And try to add edges between them like this:

a.add_connection(b)
a.add_connection(c)

When I print the connections for a, it would work fine and show it is connected to b and c. However when I print the connections to the b vertex, it shows an connection to itself and a connection to the c vertex (Same connections as the a vertex).
How would I fix it to only have connections between the intended vertices?

Upvotes: 0

Views: 30

Answers (1)

Djaouad
Djaouad

Reputation: 22776

Because the objects are all sharing the same connections dictionary, this is because default values of methods/functions are evaluated at their definition, one way to avoid this is to use something like this:

class Vertex:
    def __init__(self, value, connections=None):
        if connections is None:
            connections = {}
        
        self.value = value
        self.connections = connections

    def add_connection(self, vertex, weight=1):
        self.connections[vertex] = weight

Upvotes: 2

Related Questions