我有一个定向的多重加权图。 我想找到一个循环,其中a - > b - > c - >一个
我的图表示例。我希望它清楚:
v1 -> v2
v2 -> v3
v3 -> v1
v1 -> v4
v2 -> v5
如何只迭代目标节点? 这是我的好消息
results = []
for n in g.nodes: # iterates all nodes
x = n #marks the first node
for n1 in n.neighbors: #iterates neighbors, but this part should include only neighbors that are targets.
y = n1 # marks second node
for n2 in n.neighbors: #same as above, should select only target neighbors.
if n2 == x:
print "FOUND"
我相信应该通过使用Gython语法来做出决定,摘自Jython教程:
v1 -> v2 (or v2 <- v1): selects the directed edge from node v1 to node v2.
我的最终结果应该是:
results = [[v1,v2,v3]]
答案 0 :(得分:0)
确定一些图形库将带来此功能。如果你想手工做,也许这(快速和肮脏,Dijkstra会杀了我)片段可能会给你一些提示:
(我从v5到v2添加了另一个顶点,以便获得多个循环)
#! /usr/bin/python3
class Node:
def __init__ (self, name):
self.name = name
self.neighbours = []
def connect (self, other):
self.neighbours.append (other)
def paths (self, path = None):
path = path [:] if path else []
if self in path: return [path + [self] ]
path.append (self)
paths = []
for neighbour in self.neighbours:
paths.extend (neighbour.paths (path) )
return paths if paths else [path]
def cycles (self):
paths = self.paths ()
return [path for path in paths if len (path) > 1 and path [-1] == self]
def __repr__ (self):
return self.name
nodes = [Node ('v1'), Node ('v2'), Node ('v3'), Node ('v4'), Node ('v5') ]
nodes [0].connect (nodes [1] )
nodes [1].connect (nodes [2] )
nodes [2].connect (nodes [0] )
nodes [0].connect (nodes [3] )
nodes [0].connect (nodes [4] )
nodes [4].connect (nodes [1] )
for node in nodes:
print (node, node.cycles () )