如何修复__iter__函数

时间:2016-11-16 06:10:38

标签: python

 {'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 方法,以便每次调用next时都会生成一个值为2元组的值,该值在Graph中重复一个边:一个源节点,后跟一个目标节点。原始节点按其程度的递增顺序生成(它们有多少边缘,包括传入和传出)。并且,如果两个节点具有相同的度数,则应按字母顺序生成它们。每个源节点的目标节点应按字母顺序显示。 例如,迭代上面的原始图表会按以下顺序生成6个值:(' b',' c'),(' b',' ; d'),(' a',' c'),(' a',' d'),(&# 39; d',' a')和(' d',' c')。这是排序,因为节点b具有2级,所以它和它的两个目标节点按字母顺序排列,是第一个;节点a具有度数3,因此它和它的两个目的节点按字母顺序出现在下一个节点;最后节点d的度数为4,因此它和它的两个目标节点按字母顺序排列,是最后一个。

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功能吗?

1 个答案:

答案 0 :(得分: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')]