使用Python迭代器在有向图中查找给定顶点的事件边缘

时间:2013-04-06 11:58:06

标签: python iterator directed-graph

我正在编写一个类来查找有向图中给定顶点的入射边。该类使用迭代器遍历图中的邻接列表。但是,我无法以正确的格式返回结果。目前,我使用列表found来确定给定边是否是所考虑顶点的入射边。这种方法给出了正确的结果,但我想避免让next方法返回一个列表而是返回self.ptr.data(当前已注释掉)。

class IncidentDirectedEdgeIterator(IncidentEdgeIterator):

"""
The interface of an incident directed edge iterator data structure.
"""

def __init__( self, graph, index ):
    """
    Constructs an incident edge iterator for the specified graph.

    @param graph: The graph including the incident edges.
    @type: L{Graph}
    @param index: The index specifying the vertex of the incident edges.
    @type: C{int}
    """
    super(IncidentDirectedEdgeIterator, self).__init__( graph, index )
    self.ptr = None
    self.graph = graph

def next( self ):
    """
    Returns the next incident edge in the graph. If there are no
    further edges, the StopIteration exception is raised.

    @raises: StopIteration if all incident edges have been enumerated.
    @type: C{StopIteration}
    @return: The next incident edge in the graph.
    @rtype: C{object}
    """
    found = []
    if self.ptr is None:
        i = 0
        while i >= 0 and i < self.graph.getNumberOfVertices():
            ptr = self.container.adjacencyList[i].head
            while ptr is not None:
                if self.index == ptr.data.getV1().getVertexNumber():
                    if ptr not in found:
                        found.append( ptr )
                    self.ptr = ptr
                ptr = ptr.next
            i += 1
    else:
        self.ptr = self.ptr.next
    if self.ptr is None:
        raise StopIteration
    if len( found ) == 0:
        raise StopIteration
    #return self.ptr.data
    return found

使用found列表相当丑陋,我想完全避免它。建议非常感谢。

使用生成器函数代替迭代器类:

def generatorTest( self, index ):
    i = 0
    while i >= 0 and i < self.getNumberOfVertices():
        ptr = self.adjacencyList[i].head
        while ptr is not None:
            if index == ptr.data.getV1().getVertexNumber():
                yield ptr
            ptr = ptr.next
        i += 1

1 个答案:

答案 0 :(得分:1)

你缺少的是“yield”,在Python文档中查找生成器。这样,您可以逐个返回边缘,而无需创建临时列表。

此外,您的代码不是非常Pythonic,而是似乎是C代码。第一个“气味”是顶点存储在一个数组中并通过它们的索引引用。在Python中,您宁愿存储对实际顶点的引用。此外,您的“类”不应该是一个类,而是一个普通函数,它会产生与给定顶点相关的边,请参阅http://www.youtube.com/watch?v=o9pEzgHorH0

相关问题