2

次のグラフの実装では、v, w = e代入は何を行い、どのように機能しますか? そのような非対称な割り当てを行うことは許可されていないと思いました。

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
4

2 に答える 2

4

これが機能する方法は次のとおりです。e は実際には 2 つの要素で構成されるタプルです。述べるv, w = eということは、e の最初の要素を v に、2 番目の要素を w に割り当てることと同じです。

デモンストレーションとして、次の python コンソール出力を確認してください。

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

それがいくらか解決することを願っています。

于 2013-02-22T21:09:21.517 に答える
0

アラン・ダウニー () が本の次のページで開梱を見せたいからです。

ここで彼は書いています:

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__

...だから、それがタプルであることが明らかになります。

于 2013-02-22T21:16:37.920 に答える