简体   繁体   中英

In a networkx graph, how can I find nodes with no outgoing edges?

I'm working on a project similar to a random walk, and I'm currently trying to find out if it's possible, and if so how, to find out if a node in the directed networkx graph is "dangling", that is if it has no edges edges to other nodes.

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

Is there a way of checking if a node has no outgoing links in a directed graph? Or is there another method of doing this that anyone can recommend, that doesn't include using the networkx pagerank method?

Leaves have an out-degree of zero, so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM