我正在尝试实施Karger的算法,并且在使用Python中的列表时遇到了麻烦。
我有一个输入列表input_v
,它应该在整个程序中保持静态。在while循环中,我使用名为max_iters
的{{1}}列表副本进行input_v
迭代的Karger算法。在内部for循环的1次迭代结束时,似乎我在vertices
上应用的所有逻辑也应用于vertices
,即使我做input_v
。
vertices = list(input_v)
这是在第二次迭代开始后的输出。
input_v = [[[1], 2, 3, 4], [[2], 1, 4], [[3], 1, 4], [[4], 2, 3]]
# Perform Karger's n^2ln(n) times to ensure p > 1-1/n
for i in range(0, max_iters):
vertices = list(input_v)
print 'new loop'
print vertices
print input_v
#Contract edges n-2 times to find A and B
for j in range(0, n - 2):
# length of current array
len_arr = n - j
#rand_vn => random index within current array
#i_vn => true index of vertex from orig array
# Randomly select 1st vertex (v1) to contract
rand_v1 = randint(1, len_arr) - 1
i_v1 = vertices[rand_v1][0][0]
# Randomly select 2nd vertex (v2) connected to v1
i_in_v1 = randint(1,len(vertices[rand_v1]) - 1)
i_v2 = vertices[rand_v1][i_in_v1]
for k in range(0, len_arr):
if i_v2 in vertices[k][0]:
rand_v2 = k
for y in vertices[rand_v2][1:]:
if y not in vertices[rand_v1]:
vertices[rand_v1].append(y);
# Remove each other's indices from list of edges
for q in vertices[rand_v2][0]:
if q in vertices[rand_v1]:
vertices[rand_v1].remove(q)
# Add indices from v2 to v1 (supernode)
vertices[rand_v1][0].append(q)
for r in vertices[rand_v1][0]:
if r in vertices[rand_v1]:
vertices[rand_v1].remove(r)
vertices.pop(rand_v2)
print vertices
del vertices[:]