Deep copy a list in Python -
i have problem list copy:
so after got e0
'get_edge'
, make copy of e0
calling 'e0_copy = list(e0)'
. here guess e0_copy
deep copy of e0
, , pass e0_copy
'karger(e)'
. in main function.
why result of 'print e0[1:10]'
before loop not same after loop?
below code:
def get_graph(): f=open('kargermincut.txt') g={} line in f: ints = [int(x) x in line.split()] g[ints[0]]=ints[1:len(ints)] return g def get_edge(g): e=[] in range(1,201): 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 == 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] ## result not equal print2 k in range(1,5): e0_copy=list(e0) ## guess here e0_coypy deep copy of e0 results.append(karger(e0_copy)) #print "the result %d" %min(results) print e0[1:10] ## print2
thanks in advance!
e0_copy
not deep copy. don't make deep copy using list()
(both list(...)
, testlist[:]
shallow copies).
you use copy.deepcopy(...)
deep copying list.
deepcopy(x, memo=none, _nil=[]) deep copy operation on arbitrary python objects.
see following snippet -
>>> = [[1, 2, 3], [4, 5, 6]] >>> b = list(a) >>> [[1, 2, 3], [4, 5, 6]] >>> b [[1, 2, 3], [4, 5, 6]] >>> a[0][1] = 10 >>> [[1, 10, 3], [4, 5, 6]] >>> b # b changes -> not deepcopy. [[1, 10, 3], [4, 5, 6]]
now see deepcopy
operation
>>> import copy >>> b = copy.deepcopy(a) >>> [[1, 10, 3], [4, 5, 6]] >>> b [[1, 10, 3], [4, 5, 6]] >>> a[0][1] = 9 >>> [[1, 9, 3], [4, 5, 6]] >>> b # b doesn't change -> deep copy [[1, 10, 3], [4, 5, 6]]
Comments
Post a Comment