entrepaul
entrepaul

Reputation: 947

Adding an edge in a Python graph (beginner)

In the following implementation of a graph, what does the v, w = e assignment do and how does it work? I thought we are not allowed to do an asymmetrical assignment like that.

class Graph(dict):
    def __init__(self, vs=[], es=[]):
        """create a new graph.  (vs) is a list of vertices;
        (es) is a list of edges."""
        for v in vs:
            self.add_vertex(v)

        for e in es:
            self.add_edge(e)

    def add_vertex(self, v):
        """add (v) to the graph"""
        self[v] = {}

    def add_edge(self, e):
        """add (e) to the graph by adding an entry in both directions.

        If there is already an edge connecting these Vertices, the
        new edge replaces it.
        """
        v, w = e
        self[v][w] = e
        self[w][v] = e

Upvotes: 2

Views: 1077

Answers (2)

root-11
root-11

Reputation: 1806

It is because Allan Downey (book) wants to show you unpacking on the next page in his book.

Here he writes:

class Edge(tuple):
    def __new__(cls, *vs):
        return tuple.__new__(cls, vs)

    def __repr__(self):
        return 'Edge(%s, %s)' % (repr(self[0]), repr(self[1]))

    __str__ = __repr__

...so it becomes explicit that it's a tuple.

Upvotes: 0

MrHug
MrHug

Reputation: 1315

The way it works is like this: e is actually a tuple, consisting of two elements. Stating v, w = e is equal to assigning the first element of e to v and the second to w.

As a demonstration, check the following python console output:

>>> e = (1, 2)
>>> u, v = e
>>> u
1 
>>> v
2

Hope that clears it up somewhat.

Upvotes: 4

Related Questions