gpt4 book ai didi

python - 排列具有随机边的图

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:39 25 4
gpt4 key购买 nike

我正在使用 python 和 networkx 将边随机分配给点头。点头分为三类(白色、黑色和其他),每个类别有 33 个节点。代码有效,但我有两个问题:1-如何确保一个节点不会被选中两次?我的意思是说在第一轮中节点 4 和 56 之间定义了一条边。我如何确保在第 4 轮中不会再次选择这条边?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/

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