I was trying to implement a (naive)quick_find_union as follows
class QF(object):
def __init__(self,N):
self.id=[x for x in range(N)]
def connected(self,p,q):
assert type(p)==int
assert type(q)==int
return self.id[p]==self.id[q]
def union(self,p,q):
assert type(p)==int
assert type(q)==int
for x in self.id:
pid=self.id[p]
qid=self.id[q]
if x==pid:
x=qid
# for i in range(len(self.id)):
# pid=self.id[p]
# qid=self.id[q]
# if self.id[i]==pid:
# self.id[i]=qid
def show_array(self):
print self.id
if __name__=='__main__':
qf=QF(10)
qf.show_array()
print qf.connected(1,4)
qf.union(1,4)
qf.show_array()
print qf.connected(1,4)
This returns
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
False
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
False
but when I use only the commented out portion in method union
,it works as expected
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
False
[0, 4, 2, 3, 4, 5, 6, 7, 8, 9]
True
Why is this happening? Has it got something to do with trying to modify the elements of array while iterating? I am not very clear about this..Can someone please explain?
x=qidjust rebind the namexto the object which the nameqidrefer to. It doesn’t modify the element inself.idlist.use
enumerate()to get the both the index and value, and update theself.idlist by using the index: