简体   繁体   中英

modifying elements of array in python

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=qid just rebind the name x to the object which the name qid refer to. It doesn't modify the element in self.id list.

use enumerate() to get the both the index and value, and update the self.id list by using the index:

for i, x in enumerate(self.id):
    pid=self.id[p]
    qid=self.id[q]
    if x==pid:
        self.id[i]=qid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM