简体   繁体   English

Sage为什么将局部python变量视为全局变量?

[英]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? 我试图定义以下作用于输入列表A的函数,但是每次输入该函数都会影响A的全局值。如何使它在本地运行?

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. 我试过设置B=A并在所有地方都替换B,但这也不起作用,我也不知道。 Do I need to declare some sort of sage-y variable thing? 我需要声明某种Sage-y变量吗?

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! 非常感谢!

You are passing a reference to a container object to your listxgcd function and the function retrieves elements from that container using pop . 您正在listxgcd容器对象的引用传递给listxgcd函数,该函数使用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])
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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