gpt4 book ai didi

python - 在networkx图中,如何找到没有传出边的节点?

转载 作者:行者123 更新时间:2023-12-02 18:26:29 24 4
gpt4 key购买 nike

我正在开发一个类似于随机游走的项目,我目前正在尝试找出是否可能,如果可能的话如何找出有向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 方法?

最佳答案

叶子的出度为零,因此:

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

关于python - 在networkx图中,如何找到没有传出边的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70085530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com