Python 图中获取边界顶点的可伸缩函数

Python 图中获取边界顶点的可伸缩函数,python,igraph,hierarchical-clustering,Python,Igraph,Hierarchical Clustering,给定一个社区划分,我需要一个在多个社区中具有边的顶点列表,即边界顶点 我试过这个: import igraph import time if __name__ == "__main__": g = igraph.Nexus.get("condmatcollab2005") tic = time.clock() cl = g.community_fastgreedy() membership = cl.as_clustering().membership

给定一个社区划分,我需要一个在多个社区中具有边的顶点列表,即边界顶点

我试过这个:

import igraph
import time

if __name__ == "__main__":
    g = igraph.Nexus.get("condmatcollab2005")

    tic = time.clock()
    cl = g.community_fastgreedy()
    membership = cl.as_clustering().membership
    print "community time: "+str(time.clock() - tic)

    # --> Do I need to leave this part more faster =======
    tic = time.clock()
    boundary = []
    visited = set()
    for vertex in g.vs():
        if vertex.index in visited: continue
        for neighbor in g.neighbors(vertex.index):
            if membership[vertex.index] != membership[neighbor]:
                boundary.append(vertex.index)
                visited.add(vertex.index)
                if neighbor not in visited:
                    boundary.append(neighbor)
                    visited.add(neighbor)
                break
    print "boundary time: "+str(time.clock() - tic)
这种实现非常缓慢。我不知道是否有更快或更干净的方法来做到这一点

例如,通过使用
cl.as_clustering()
对象或其他更有效的数据结构,可能有一种更快的方法


我需要一些关于如何优化我的代码的帮助!我是否需要更快地保留代码。

cl返回的
VertexClustering
对象。as_clustering()
有一个
crossing()
方法-这将为簇间的边提供一个布尔向量,其中包含
True
,为簇内的边提供
False
。可以像这样轻松提取交叉边的索引:

cl = g.community_fastgreedy().as_clustering()
crossing_edges = [index for index, is_crossing in enumerate(cl.crossing()) if is_crossing]
然后,只需获取每条边并将其端点放入一个集合:

boundary = set()
for edge in g.es[crossing_edges]:
    boundary.update(edge.tuple)

你的问题到底是什么?询问“改进我的代码的建议”不太适合这个网站。@Hooked我需要一些关于如何优化我的代码的帮助。我需要更快地离开我的代码吗?也许你可以在代码审查网站上浏览一下,这个问题可能就在那里。非常有趣。谢谢@Tamás。