繁体   English   中英

如何修复__iter__函数

[英]How to fix the __iter__ function

 {'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中的一条边:一个原始节点,后跟一个目标节点。 原始节点按其度数的递增顺序生成(它们有多少条边(入站和出站))。 并且,如果两个节点的度数相同,则应按字母顺序生成它们。 每个原始节点的目标节点应按字母顺序显示。 例如,对上面的原始Graph进行迭代将按以下顺序生成6个值:('b','c'),('b','d'),('a','c'),('a ','d'),('d','a')和('d','c')。 这是顺序,因为节点b的阶数为2,所以它和它的两个目标节点(按字母顺序显示)是第一个; 节点a的度数为3,因此它和它的两个目标节点(按字母顺序显示)是下一个; 最后,节点d的阶数为4,因此它和它的两个目标节点(按字母顺序显示)位于最后。

节点

调用时,我正在使用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'

有人可以帮助我修复迭代功能吗?

您可以使用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')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM