你有什麼想法我沒有增加?我試圖用n個節點生成一個加權圖?爲什麼我的python代碼無限循環?
我是我的增量。
所以,如果我叫genWeightGraph(10),我想增加10個節點,增加節點k到兩個頂點(v1和v2)。我開始我的圖形僅用兩個彼此連接的節點,因此開始時其邊緣的列表爲[[1],[0]],其中列表的索引[索引] =頂點。我從一組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