胡海华分享 http://blog.sciencenet.cn/u/jgshuhaihua

博文

NetworkX 实现1:寻找三元组

已有 4940 次阅读 2010-10-15 14:39 |个人分类:NetworkX学习笔记|系统分类:科研笔记

思路:
前提假设:有一个存储节点ID的dictionary which point to a sequence of their neighbors, 且是有向图.

def generate_triangles(nodes):
    """Generate triangles. Weed out duplicates."""
    visited_ids = set() # remember the nodes that we have tested already
    for node_a_id in nodes:
        for node_b_id in nodes[node_a_id]:
            if node_b_id == node_a_id:
                continue # nodes shouldn't point to themselves
            if node_b_id in visited_ids:
                continue # we should have already found b->a->??->b
            for node_c_id in nodes[node_b_id]:
                if node_c_id in visited_ids:
                    continue # we should have already found c->a->b->c
                if node_a_id in nodes[node_c_id]:
                    yield(node_a_id, node_b_id, node_c_id)
        visited_ids.add(node_a_id) # don't search a - we already have all those cycles

实现:

from random import randint
n = 1000
node_list = range(n)
nodes = {}
for node_id in node_list:
    node = tuple()
    for i in range(randint(0,10)): # add up to 10 neighbors
        try:
            neighbor_id = node_list[node_id+randint(-5,5)] # pick a nearby node
        except:
            continue 
        if not neighbor_id in node:
            node = node + (neighbor_id,)
    nodes[node_id] = node

cycles = list(generate_triangles(nodes))
print len(cycles)



https://wap.sciencenet.cn/blog-243747-373567.html

上一篇:NetworkX画图的小技巧
下一篇:NetworkX实现2:超大网络数据处理变通
收藏 IP: .*| 热度|

0

发表评论 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-20 06:05

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部