Mkl Rjv
Mkl Rjv

Reputation: 6933

Python: A variable which is assigned and not changed changes along with another

Working in Sage which is basically python, I believe. I gave the following code.

def lfsr_1(regs,tabs):
    I=regs
    leng=len(I)
    count=0
    while True:
        FB=0
        print "Before"
        print I
        print regs
        print temp
        for i in range(0,leng):
            FB=FB+tabs[i]*I[i]   //Calculating the feedback value
        for i in range(0,leng):
            regs[leng-(i+1)]=regs[leng-(i+1)-1] //Shifting regs one bit to the right
        I[0]=FB   //Adding the feedback at the end
        count=count+1  //Incrementing count value which will contain the periodicity
        print "After"
        print I
        print regs
        print temp
        if (I==regs):   //End when the initial state is repeated again. Now, count will contain the periodicity
            break

The input variables were in initialized as follows

tabs=[GF(2)(1),0,0,1,1,1]
regs=[GF(2)(0),1,1,0,1,1]
temp=regs

However, Im getting an output as:

Before
[0, 0, 1, 1, 0, 1]
[0, 0, 1, 1, 0, 1]
[0, 0, 1, 1, 0, 1]
After
[0, 0, 0, 1, 1, 0]
[0, 0, 0, 1, 1, 0]
[0, 0, 0, 1, 1, 0]

Dont know how this happens as 'I' changes along with 'regs'. 'I' is never changed in code. Is there something wrong with my assignment?

Addendum:Trying to implement a Linear Feedback Shift Register. The code is to calculate the periodicity of an LFSR. regs is the intial state, I is used to check when the regs returns to the initial state again(to calculate periodicity) and temp is just a test variable to see if another initialized variable would also be shifted.

Upvotes: 0

Views: 108

Answers (2)

Imre Kerr
Imre Kerr

Reputation: 2428

The problem lies in the line

I=regs

When you do this, you do not copy the contents of regs, you copy the reference to regs. Thus making I and regs the same array.

Upvotes: 1

Ray Toal
Ray Toal

Reputation: 88418

Of course I changes along with regs because you made this assignment:

I=regs

Now I and regs reference the same list. That is how Python works. A list variable simply references a list object, it doesn't contain the whole list object.

Here's an example:

a = [1,2,3]
b = a
a[1] = 100
print b

Perhaps you wanted to make I be a copy of regs.

Try:

I = regs[:]

Of course, you might have "structural sharing" if reg contains objects.

Upvotes: 2

Related Questions