2016-11-16 86 views
0
{'a': [{'c','d'}, {'d'}  ], 
'b': [{'c','d'}, set()  ], 
'c': [set(),  {'a','b','d'}], 
'd': [{'a','c'}, {'a','b'} ], 
'e': [set(),  set()  ]} 

class Graph: 
    def __init__(self,*args): 
     self.edges = {} 

    def degree(self,n): 
     count = 0 
     if n not in self.edges.keys(): 
      raise GraphError 
     for key,value in self.edges.items(): 
      if key == n: 
       for c in value: 
        for x in c: 
         count += 1 
     return count 

    def __iter__(self): 
     l=[] 
     for key,value in self.edges.items(): 
      for item in value[0]: 
       l.append((key,item)) 
     return sorted(l, key = degree(l[0])) 

定義一條ITER方法使得每個呼叫到下一個產生一個值,該值是一個2元組repesenting在圖中的邊:源節點,接着它的目的地節點中的一個。原始節點按其度數遞增的順序生成(它們具有多少條邊,即傳入和傳出)。而且,如果兩個節點具有相同的學位,則應按字母順序製作。每個源節點的目標節點應按字母順序顯示。例如,對上面的原始圖進行迭代,按以下順序產生6個值:('b','c'),('b','d'),('a','c'),(' a',d'),('d','a')和('d','c')。這是排序,因爲節點b的等級爲2,所以它和它的兩個目標節點按字母順序排列,是第一個;節點a的等級爲3,所以它和它的兩個目的節點按字母順序出現,最後節點d具有度數4,所以它和它的兩個目的地節點按字母順序排列,是最後一個。如何修復__iter__函數

node

我在ITER功能工作,當它調用

g = Graph() 
g.edges = {'a': [{'c','d'},{'d'}], 'b': [{'c','d'}, set()], 'c': [set(),{'a','b','d'}], 'd': [{'a','c'},{'a','b'}], 'e': [set(),set()]} 

它應該返回

[t for t in g]-->[('b', 'c'), ('b', 'd'), ('a', 'c'), ('a', 'd'), ('d', 'a'), ('d', 'c')] 

但是當我打電話給我ITER功能,它產生以下錯誤:

96 *Error: [t for t in g] raised exception TypeError: iter() returned non-iterator of type 'list' 
    99 *Error: [t for t in g] raised exception TypeError: iter() returned non-iterator of type 'list' 
    102 *Error: [t for t in g] raised exception TypeError: iter() returned non-iterator of type 'list' 

有人可以幫助我解決我的iter功能嗎?

回答

0

您可以使用generator來實現__iter__Graph。然後你只需要與元組鍵(degree, name)頂點進行排序,在它們之間迭代和yield邊緣按字母順序排列:

EDGES = { 
    'a': [{'c','d'}, {'d'}  ], 
    'b': [{'c','d'}, set()  ], 
    'c': [set(),  {'a','b','d'}], 
    'd': [{'a','c'}, {'a','b'} ], 
    'e': [set(),  set()  ] 
} 

class Graph: 
    def __init__(self, edges): 
     self.edges = edges 

    def degree(self,n): 
     if n not in self.edges: 
      raise GraphError 
     return sum(len(s) for s in self.edges[n]) 

    def __iter__(self): 
     # Iterate over vertices, primary key is degree and 
     # secondary is name 
     for v in sorted(self.edges, key=lambda x: (self.degree(x), x)): 
      # Iterate over outgoing edges in alphabetical order 
      for other in sorted(self.edges[v][0]): 
       yield v, other 

g = Graph(EDGES) 
print(list(iter(g))) 

輸出:

[('b', 'c'), ('b', 'd'), ('a', 'c'), ('a', 'd'), ('d', 'a'), ('d', 'c')] 
相關問題