python - 排列具有随机边的图

标签 python random graph networkx

我正在使用 python 和 networkx 随机分配边缘给节点。节点分为三类(白色、黑色和其他),每个类别有 33 个节点。代码有效,但我有两个问题: 1-如何确保一个节点不会被选择两次?我的意思是说,在第一轮中,在节点 4 和 56 之间定义了一条边。我如何确保在第四轮中,这条边不会再次被选择? 2-我想做的下一步是分配权重。例如,这意味着如果 x 是白色,则 y 为白色的可能性增加 A%。我怎样才能将其添加到此?

import networkx as nx
import matplotlib.pyplot as plt
import random
import numpy

G=nx.Graph()
w=1
b=34
o=67

while w < 34:
    G.add_node(w, race='white')
    w+=1
while b < 67:
    G.add_node(b, race='black')
    b+=1
while o < 100:
    G.add_node(o, race='other')
    o+=1


from numpy import random as rand
###first round edges assignment
num1edge = int(raw_input("Please enter number of edges you want to start with: "))
i=0
while i< num1edge:
    x1 = rand.randint (1, 99)
    y1 = rand.randint (x1, 99)
    G.add_edge(x1,y1)
    i+=1

numrounds = int(raw_input("Please enter how many times you want to run: "))
numedge = int(raw_input("Please enter number of edges you want to be created in each round: "))                      
j = 0
k = 0
while j < numrounds:
    while k  < num1edge:
        x = rand.randint (1, 99)
        y = rand.randint (x, 99)
        G.add_edge(x,y)
        k+=1
    j+=1
nx.draw(G)
plt.show() 

最佳答案

使用邻接矩阵。行和列之间的截距给出了节点之间的关系。例如,假设您只有 3 个节点。 1、2 和 3,所以如果你有下一个矩阵

     1   2   3
     _________
1 |  0   0   0
2 |  0   0   1
3 |  0   0   0 

这意味着节点 2 和 3 之间的边已被选择。如果您选择另一个,例如 (1,2),只需更新您的矩阵:

your_matrix[1][2] = 1

关于python - 排列具有随机边的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20486107/

相关文章:

python - Django csrf token 的作用是什么?

android - 整数数组中随机选择的索引导致崩溃

用曲线连接图中点的算法

c++ - 我的 vector vector 有什么问题?

python - 计算风险值(value)或 "most probable loss",对于给定的返回分布

python - 为什么 Django 没有查看权限?

javascript - 通过 React js 从具有属性的项目列表中获取随机项目

Javascript随机背景图片

相当于 D3.js 的 Python

python - `numpy.sum` 与 `ndarray.sum`