你知道我没有增加什么吗?我正在尝试使用n个节点生成加权图?
我是我的增量。
因此,如果我调用genWeightGraph(10),我想添加10个节点,将节点k添加到两个顶点(v1和v2)。我只用两个相互连接的节点开始我的图形,因此它们的边缘列表开始为[[1],[0]],其中list [index] = vertex的索引。我从一组N个节点中随机生成k,并且我将K连接到2个随机顶点。
列表加权存在是因为,与互联网一样,您拥有的连接/边缘越多,新节点连接到您的可能性就越大。因此,当我从此加权列表中提取/采样时,加权列表可以帮助我解释这种概率偏差。
但它并没有结束。永远。我无法理解。
def genWeightGraph(n): #n nodes, davg number of links
links = [[] for i in xrange(n-2)] # create n many nodes -2 to adjust for insert [1],[0]
links.insert(0,[1])
links.insert(1,[0]) # start with [[1],[0],...[]] of n length
weighted = [nodes for v in links for nodes in v] #initialized weighted list of [1,0]
i = 0 #initialized edges added
while (i < n): #add this many nodes
v1 = random.choice(weighted) #pick a friend/vertex from weighted list
v2 = random.choice(weighted) #pick another friend/vertex from weighted list
k = random.choice(xrange(2,n)) #pick a new friend to connect both v1 and v2 to
print "v1", v1
print "v2", v2
print "k", k
print "nodes", i
if k in links[v1] or links[v2]:
continue
elif v1 == v2: # if you pick the same vertex, just add k to one of them
links[v1].append(k)
links[k].append(v1)
weighted += [k,v1]
i += 1
else:
links.insert(v1, k) # access v1's friend list, append k
links.insert(k, v1) # find k's list, add v
links.insert(v2, k) #add k to v2's list
links.insert(k, v2) #find k's list, add v2
weighted += [k,v1,k,v2] #add to weighted
i += 1
答案 0 :(得分:2)
这是问题所在:
if k in links[v1] or links[v2]:
不是你如何使用或运算符......应该是:
if (k in links[v1]) or (k in links[v2]):
在您的代码中,一旦链接[v2]初始化,您始终会获得真值。
考虑以下示例
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> if 3 in a or b: print 'ok'
...
ok
>>> if 13 in a or b: print 'bad'
...
bad
>>> if 13 in a or 13 in b: print 'bad'
...
>>>
答案 1 :(得分:0)
您有以下一行
if k in links[v1] or links[v2]:
测试k
是in links[v1]
还是links[v2]
不为空。将其更改为
if (k in links[v1]) or (k in links[v2]):
答案 2 :(得分:-2)
因此:
if k in links[v1] or links[v2]:
continue