2013-02-22 2 views
1

그래프의 다음 구현에서 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 
+0

"언 패킹"이라고합니다 - 예를 들어'a, b = [1, 2]' –

답변

3

작동 방식은 다음과 같이이다 : 전자는 두 가지 요소로 구성, 실제로 튜플이다. v, w = e은 e의 첫 번째 요소를 v에 할당하고 두 번째 요소를 w에 할당하는 것과 같습니다.

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

희망 다소 그것을 웁니다

는 데모, 다음 파이썬 콘솔 출력을 확인합니다.

0

Allan Downey (book)가 자신의 책에서 다음 페이지에 포장 풀기를 보여주기 때문입니다.

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__ 

을 ... 그래서 그것은 튜플 있다고 명시된다 :

는 여기에서 그는 기록합니다.

관련 문제