如何为networkx中的边缘分配随机权重,例如边缘(a,a)的权重= 0和边缘(a,b)的权重= K,其中K是某个随机数

时间:2019-05-05 18:32:56

标签: python-3.x networkx

我正在处理加权图,我想为图的边缘分配随机权重,这样,

 weight of edge(a, a) = 0
 weight of (a, b) = weight of edge(b, a) = K

其中K是一些随机数。对于图的所有边缘都是这样。

为此,我正在使用random.randint()方法。我实际上是在使用求和逻辑。如果两条边的总和相同,则分配一些随机整数。

这是我的代码,

nodelist = list(range(1, num_nodes + 1))
edgelist = []
for i in nodelist:
    for j in nodelist:
        if i == j:
            edgelist.append((i, j, 0))
        if (i != j and sum((i, j)) == sum((j, i))):
            rand = random.randint(5, 25)
            edgelist.append((i, j, rand))
print(edgelist)

实际结果

[(1, 1, 0), (1, 2, 18), (1, 3, 6), (2, 1, 13), (2, 2, 0), (2, 3, 21), (3, 1, 20), (3, 2, 17), (3, 3, 0)]

预期结果,

[(1, 1, 0), (1, 2, K), (1, 3, H), (2, 1, K), (2, 2, 0), (2, 3, P), (3, 1, H), (3, 2, P), (3, 3, 0)]

其中KHP是一些随机整数。

2 个答案:

答案 0 :(得分:2)

如果结果的顺序不重要,则以下代码将提供所需的输出:

import random
num_nodes = 3
nodelist = list(range(1, num_nodes + 1))
edgelist = []
for i in nodelist:
    for j in nodelist:
        if j > i:
            break
        if i == j:
            edgelist.append((i, j, 0))
        else:
            rand = random.randint(5, 25)
            edgelist.append((i, j, rand))
            edgelist.append((j, i, rand))
print(edgelist)
# [(1, 1, 0), (2, 1, 7), (1, 2, 7), (2, 2, 0), (3, 1, 18), (1, 3, 18), (3, 2, 13), (2, 3, 13), (3, 3, 0)]

如果需要对边缘进行排序,只需使用:

print(sorted(edgelist))
# [(1, 1, 0), (1, 2, 20), (1, 3, 16), (2, 1, 20), (2, 2, 0), (2, 3, 23), (3, 1, 16), (3, 2, 23), (3, 3, 0)]

答案 1 :(得分:0)

所以我想出了一些有趣的东西。在下面的矩阵中说出5个节点的完整图中的边,

[1, 1]  [1, 2]  [1, 3]  [1, 4]  [1, 5]
[2, 1]  [2, 2]  [2, 3]  [2, 4]  [2, 5]
[3, 1]  [3, 2]  [3, 3]  [3, 4]  [3, 5]
[4, 1]  [4, 2]  [4, 3]  [4, 4]  [4, 5]
[5, 1]  [5, 2]  [5, 3]  [5, 4]  [5, 5]

现在,从principal diagonal移到右侧,我们得到了第一个元素小于第二个元素的列表。我们只需要针对它们并为其append新设置随机权重。

这是我的代码,

nodelist = list(range(1, num_nodes + 1))
edgelist = []
for i in nodelist:
    for j in nodelist:
        edgelist.append([i, j])

p = 0
eff_edgelist = []
while p < len(edgelist):
    if edgelist[p][0] <= edgelist[p][1]:
        eff_edgelist.append(edgelist[p])
    p += 1

for i in eff_edgelist:
    if i[0] == i[1]:
        i.append(0)
    else:
        i.append(random.randint(5, 50))
eff_edgelist = [tuple(i) for i in eff_edgelist]

for i in list(G.edges(data=True)):
    print([i])

和结果

[(1, 1, {'weight': 0})]
[(1, 2, {'weight': 12})]
[(1, 3, {'weight': 37})]
[(1, 4, {'weight': 38})]
[(1, 5, {'weight': 6})]
[(2, 2, {'weight': 0})]
[(2, 3, {'weight': 12})]
[(2, 4, {'weight': 40})]
[(2, 5, {'weight': 8})]
[(3, 3, {'weight': 0})]
[(3, 4, {'weight': 15})]
[(3, 5, {'weight': 38})]
[(4, 4, {'weight': 0})]
[(4, 5, {'weight': 41})]
[(5, 5, {'weight': 0})]

,如果您选中print(G[2][1]),则输出将为{'weight': 12}

表示weight of edge(a, b) = weight of edge(b, a)