2

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!

isedev
  • 18,848
  • 3
  • 60
  • 59
spitespike
  • 179
  • 3
  • 3
    the answer here is very useful http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference – Pruthvikar Mar 10 '14 at 00:29

1 Answers1

1

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])
    ...
isedev
  • 18,848
  • 3
  • 60
  • 59
  • Thanks isedev! I end up having to use the syntax copy.copy(Ain) – spitespike Mar 10 '14 at 01:41
  • Note that this has nothing to do with Sage. This is the normal Python behavior. The only modification Sage does on Python behavior is [preparsing](http://www.sagemath.org/doc/reference/misc/sage/misc/preparser.html) when you are using command interpreter (no preparse is done when importing a Python file). – hivert Mar 10 '14 at 08:10
  • @hivert that's right, I should have made that explicit. – isedev Mar 10 '14 at 10:27