我正在尝试使用python 2.7构建一个可迭代的图类。我希望能够通过包含顶点的字典进行迭代。
从https://github.com/joeyajames切割和粘贴让我到目前为止,但现在我对如何使这项工作感到困惑,以便 我可以测试顶点dict是否存在顶点,如果不存在则添加。这部分可能是不必要的。 "如果(不是gra):"因为验证是在Graph类本身完成的。
预期输出是顶点为键的字典。 Actualy我甚至不确定列表不是更好的对象使用。
class Vertex(object):
def __init__(self, n):
self.name = n
self.neighbors = list()
self.discovery = 0
self.finish = 0
self.color = 'black'
def add_neighbor(self, v):
if v not in self.neighbors:
self.neighbors.append(v)
self.neighbors.sort()
class Graph(object):
def __init__(self,size):
self.vertices = {}
self.hops = 0
self.count = 0
self.limit = size
def __iter__(self):
return self
def next(self):
self.count += 1
if self.count > self.limit:
raise StopIteration
def add_vertex(self,vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
self.vertices[vertex.name] = vertex
return True
else:
return False
def add_edge(u,v):
if u in self.vertices and v in self.vertices:
for key, value in self.vertices.items():
if key == u:
value.add_neighbor(v)
if key == v:
value.add_neighbor(u)
return True
else:
return False
def _dfs(self, vertex):
global hops
vertex.color = 'red'
vertex.discovery = hops
hops += 1
for v in vertex.neighbors:
if self.vertices[v].color == 'black':
self._dfs(self.vertices[v])
vertex.color = 'blue'
vertex.finish = hops
time += 1
input = ((5,3),(4 ,2),(0,1),(2 3),(0 4))
N,l = input[0]
print "N is " + str(N)
print "l is " + str(l)
gra = Graph(N)
for i in xrange(1,l):
a,b = input[i]
# Store a and b as vertices in graph object
print "a is " + str(a) + " b is " + str(b)
if (a not in gra ):
print "adding a"
gra.add_vertex(Vertex(chr(a)))
if (b not in gra ):
print "adding b"
gra.add_vertex(Vertex(chr(b)))
答案 0 :(得分:2)
您正在尝试使用not in
来测试包含;实施__contains__
hook以促进:{/ p>
def __contains__(self, vertex):
return vertex.name in self.vertices
我假设你想测试顶点,所以在测试收容之前先创建一个顶点:
a = Vertex(chr(a))
if a not in gra:
print "adding a"
gra.add_vertex(a)
对于迭代,我不会让Graph
本身成为迭代器;这限制了您只需迭代 。您的next()
方法也缺少return
语句,因此您所做的就是生成一系列None
个对象。
改为使其成为 iterable ,因此每次调用__iter__
时都返回一个新的迭代器对象。您最简单的方法是将__iter__
设为generator:
def __iter__(self):
for vertex in self.vertices.itervalues():
yield vertex
请注意yield
。我以为你想迭代顶点。