我正在编写一个类来查找有向图中给定顶点的入射边。该类使用迭代器遍历图中的邻接列表。但是,我无法以正确的格式返回结果。目前,我使用一个列表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