Skip to main content
 首页 » 编程设计

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

2025年05月04日10emanlee

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

类 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 

请您参考如下方法:

您缺少的是“ yield ”,请在 Python 文档中查找生成器。有了它,您可以一条一条地返回边缘,而无需创建临时列表。

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