我想用python 2.7構建一個可迭代的圖類。我想能夠遍歷包含頂點的字典。使用字典對圖類進行迭代
從https://github.com/joeyajames切割和粘貼到目前爲止,但現在我很困惑如何使這項工作,以便我可以測試頂點字典的存在的頂點,如果不存在添加。這部分可能不需要。 「if(a not in gra):」因爲驗證是在Graph類本身完成的。
期望的輸出是一個以頂點爲關鍵字的字典。實際上我甚至不確定列表是不是更好的對象使用。
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)))
遏制測試和迭代是*兩個單獨的事情*。你的'next()'方法在迭代時也不會產生任何東西。 –