I have just started using SAGE which is pretty close to python as I understand it, and I have come accross this problem where I'll have as a parameter of a function a matrix which I wish to use multiple times in the function with its same original function but through the different parts of the function it changes values.
I have seen in a tutorial that declaring a variable in the function as variable = list(parameter)
doesnt affect the parameter or whatever is put in the parentheses. However I can't make it work.. Below is part of my program posing the problem (I can add the rest if necessary): I declare the variable determinant
which has as value the result of the function my_Gauss_determinant
with the variable auxmmatrix
as parameter. Through the function my_Gauss_determinant
the value of auxmmatrix
changes but for some reason the value of mmatrix
as well. How can avoid this and be able to re-use the parameter mmatrix
with its original value?
def my_Cramer_solve(mmatrix,bb):
auxmmatrix=list(mmatrix)
determinant=my_Gauss_determinant(auxmmatrix)
if determinant==0:
print
k=len(auxmmatrix)
solution=[]
for l in range(k):
auxmmatrix1=my_replace_column(list(mmatrix),l,bb)
determinant1=my_Gauss_determinant(auxmmatrix1)
solution.append(determinant1/determinant0)
return solution
What you want is a copy of mmatrix
. The reason list(other_list)
works is because it iterates through every item in other_list
to create a new list. But the mutable objects within
the list aren't copied
>>> a = [{1,2}]
>>> b = list(a)
>>> b[0].add(7)
>>> a
[set([1,2,7])]
To make a complete copy, you can use copy.deepcopy
to make copies of the elements within the list
>>> import copy
>>> a = [{1,2}]
>>> b = copy.deepcopy(a)
>>> b[0].add(7)
>>> a
[set([1,2])]
So if you only want to copy the list, but don't want to copy the elements within the list, you would do this
auxmmatrix = copy.copy(matrix)
determinant = my_Gauss_determinant(copy.copy(matrix))
If you want to copy the elements within the list as well, use copy.deepcopy
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句