在加权有向多重图中寻找圈(Gephi,Jython,Python)

2024-09-29 01:36:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有向多重加权图。 我想找到a->;b->;c->;a的循环

我的图表样本。我希望它清楚:

v1 -> v2
v2 -> v3
v3 -> v1
v1 -> v4
v2 -> v5

如何只迭代目标节点? 这是我的鞋

^{pr2}$

我认为应该通过使用Gython语法来做出决定,这是Jython教程的摘录:

v1 -> v2 (or v2 <- v1): selects the directed edge from node v1 to node v2.

我的最终结果应该是:

results = [[v1,v2,v3]]

Tags: gtnode目标节点图表语法v3jython
1条回答
网友
1楼 · 发布于 2024-09-29 01:36:55

当然有些图形库会带来这个功能。如果你想用手来做,也许这个片段(又快又脏,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 () )

相关问题 更多 >