巢状清单无法正常运作 [英] Nested list doesn't work properly
问题描述
import re
def get_number(element):
re_number = re.match("(\d+\.?\d*)", element)
if re_number:
return float(re_number.group(1))
else:
return 1.0
def getvalues(equation):
elements = re.findall("([a-z0-9.]+)", equation)
return [get_number(element) for element in elements]
eqn = []
eqn_no = int(raw_input("Enter the number of equations: "))
for i in range(eqn_no):
eqn.append(getvalues(str(raw_input("Enter Equation %d: " % (i+1)))))
print "Main Matrix: "
for i in range((eqn_no)):
for j in range((eqn_no+1)):
print "\t%f" %(eqn[i][j]),
print
print
equation=[]
equation=eqn
for k in range((eqn_no-1)):
for i in range((k+1),eqn_no):
for j in range((eqn_no+1)):
if(eqn[i][j]!=0):
eqn[i][j]=eqn[i][j]-(eqn[k][j]*(equation[i][k]/eqn[k][k]))
print "Matrix After %d step: " %(k+1)
for i in range(eqn_no):
for j in range((eqn_no+1)):
print "\t%f"%(eqn[i][j]),
equation[i][j]=eqn[i][j];
print
print
输入:
25x+5y+z=106.8
64x+8y+z=177.2
144x+12y+z=279.2
输出为:
Main Matrix:
25.000000 5.000000 1.000000 106.800000
64.000000 8.000000 1.000000 177.200000
144.000000 12.000000 1.000000 279.200000
Matrix After 1 step:
25.000000 5.000000 1.000000 106.800000
0.000000 8.000000 1.000000 177.200000
0.000000 12.000000 1.000000 279.200000
Matrix After 2 step:
25.000000 5.000000 1.000000 106.800000
0.000000 8.000000 1.000000 177.200000
0.000000 0.000000 1.000000 279.200000
但是应该像
Main Matrix:
25.000000 5.000000 1.000000 106.800000
64.000000 8.000000 1.000000 177.200000
144.000000 12.000000 1.000000 279.200000
Matrix After 1 step:
25.000000 5.000000 1.000000 106.800000
0.000000 -4.80000 -1.56000 -96.208000
0.000000 -16.8000 -4.76000 -335.968000
Matrix After 2 step:
25.000000 5.000000 1.000000 106.800000
0.000000 -4.80000 -1.56000 -96.208000
0.000000 0.000000 0.699999 0.759981
首先,这是一个部分代码,用于使用朴素Guass消除方法求解n个方程式的根.有谁知道为什么发生这种情况?为什么零部分在变化而其他部分没有变化?我已经在c ++中完成了这段代码,并且在这里可以完美地工作,但是在这里我面临很多问题.也许我是python的新手.我正在使用python 2.7 .....
First of all this is a partial code for solving root of n number of equations using Naive Guass elemination method. Does anyone have any idea why the hell on earth is this happening? Why the zero parts are changing and others aren't? I have done this code in c++ and it works there perfectly but here I'm facing many problem. Maybe I'm newbie to python. I'm using python 2.7.....
推荐答案
我认为问题是作业equation = eqn
.由于eqn
是一个列表,因此它是可变的,因此作为引用传递,当您分配可变变量时,该变量实际上包含指向该对象的指针.这意味着equation
和eqn
是相同的列表.
I think the problem is the assignment equation = eqn
. Since eqn
is a list, it is a mutable and thus passed as a reference, when you assign a mutable, the variable actually contains a pointer to that object. This means that equation
and eqn
are the same list.
您应该
from copy import deepcopy
equation = deepcopy(eqn)
您需要deepcopy
而不是copy
,因为您有一个列表列表,而且内部列表也需要复制.
You need deepcopy
instead of copy
because you have a list of lists, also the inner list needs to be copied.
这篇关于巢状清单无法正常运作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!