spitespike
spitespike

Reputation: 179

Why does sage treat local python variables as global?

New to sage and python, so I'm not sure which I'm abusing. I'm trying to define the following function which acts on the input list A, but every time I input the function affects the global value of A. How can I make it behave locally?

def listxgcd( A ):
    g,s,t=xgcd(A.pop(0),A.pop(0))
    coeffs=[s,t]
    while a!=[]:
        g,s,t=xgcd(g,A.pop(0))
        coeffs=[s*i for i in coeffs]
        coeffs=coeffs+[t]
    return coeffs

I've tried setting B=A and substituting B everywhere but this doesn't work either which I don't understand. Do I need to declare some sort of sage-y variable thing?

def listxgcd( a ):
    B=a
    g,s,t=xgcd(B.pop(0),B.pop(0))
    coeffs=[s,t]
    while B!=[]:
        g,s,t=xgcd(g,B.pop(0))
        coeffs=[s*i for i in coeffs]
        coeffs=coeffs+[t]
    return coeffs

Much thanks!

Upvotes: 2

Views: 270

Answers (1)

isedev
isedev

Reputation: 19631

You are passing a reference to a container object to your listxgcd function and the function retrieves elements from that container using pop. This is not a scope issue, simply the fact there you are operating directly on the container you have passed to the function.

If you don't want the function to modify the container, make a copy of it:

import copy
def listxgcd( Ain ):
    A = copy(Ain)
    ...

Or better, access the elements using indexing, if the container allows it:

...
g,s,t=xgcd(A[0],A[1])
...
for i in range(2,len(A)):
    g,s,t=xgcd(g,A[i])
    ...

Upvotes: 1

Related Questions