我有一些問題列表副本列表:深拷貝在Python
所以我從'get_edge'
得到E0
後,我通過調用'E0_copy = list(E0)'
使E0
副本。在這裏,我猜E0_copy
是E0
的深層副本,我將E0_copy
轉換爲'karger(E)'
。但在主要功能。
爲什麼for循環之前的'print E0[1:10]'
的結果與for循環之後的結果不一樣?
下面是我的代碼:
def get_graph():
f=open('kargerMinCut.txt')
G={}
for line in f:
ints = [int(x) for x in line.split()]
G[ints[0]]=ints[1:len(ints)]
return G
def get_edge(G):
E=[]
for i in range(1,201):
for v in G[i]:
if v>i:
E.append([i,v])
print id(E)
return E
def karger(E):
import random
count=200
while 1:
if count == 2:
break
edge = random.randint(0,len(E)-1)
v0=E[edge][0]
v1=E[edge][1]
E.pop(edge)
if v0 != v1:
count -= 1
i=0
while 1:
if i == len(E):
break
if E[i][0] == v1:
E[i][0] = v0
if E[i][1] == v1:
E[i][1] = v0
if E[i][0] == E[i][1]:
E.pop(i)
i-=1
i+=1
mincut=len(E)
return mincut
if __name__=="__main__":
import copy
G = get_graph()
results=[]
E0 = get_edge(G)
print E0[1:10] ## this result is not equal to print2
for k in range(1,5):
E0_copy=list(E0) ## I guess here E0_coypy is a deep copy of E0
results.append(karger(E0_copy))
#print "the result is %d" %min(results)
print E0[1:10] ## this is print2
提前感謝!
此外,b = A [:]是一個淺合作PY。請參閱http://stackoverflow.com/questions/16270374/how-to-make-a-shallow-copy-of-a-list-in-python –