【问题标题】:In a networkx graph, how can I find nodes with no outgoing edges?在networkx图中,如何找到没有出边的节点?
【发布时间】:2021-11-24 17:20:20
【问题描述】:

我正在做一个类似于随机游走的项目,我目前正在尝试找出是否有可能,如果有的话,如何找出有向 networkx 图中的节点是否“悬空”,也就是说,如果它没有到其他节点的边。

import collections
import networkx as nx
import numpy as np
import random as rand
from collections import Counter


def randomSurf(G, moves): #with G as a directed graph and moves as the amount of "random walks"
    #rand.seed(15) #Random seed for testing consistency
    starter = rand.choice(list(G.nodes))
    currNode = starter
    m = 0.15
    #Construct list of dangling nodes
    list_of_dangl = [] #<- this is where I'm struggling.
    list_of_nodes = [starter] #List of all visited nodes, with the starting node already in it.
    for step in range(moves-1):
        if rand.random() <= m: #If the probabilty of going to a random node is hit
            currNode = rand.choice(list(G.nodes))
            list_of_nodes.append(currNode)
        else: #If the probability of going to a random node is not hit
            neighbours = list(G.edges(currNode))
            count = 0
            for _ in G.edges(currNode):
                count +=1
            tempRandom = rand.randint(0, count-1)
            currNode = neighbours[tempRandom][1]
            list_of_nodes.append(currNode)
            
    return list_of_nodes

有没有办法检查一个节点在有向图中是否没有传出链接?或者是否有其他任何人都可以推荐的方法,不包括使用 networkx pagerank 方法?

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    叶子的出度为零,所以:

    list_of_dangl = [node for node in G.nodes if G.out_degree(node) == 0]
    

    【讨论】:

    • 这正是我在路上寻找的帮助我的东西。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 2021-01-02
    • 2021-09-30
    • 2016-01-09
    • 1970-01-01
    相关资源
    最近更新 更多