[英]Why isn't my Python code for finding determinants working?
The following code in Python 3 is meant to return the determinant of any order matrix. Python 3 中的以下代码旨在返回任何阶矩阵的行列式。 It takes in a text file with the form :
它采用以下形式的文本文件:
3 6 8 9
3 6 8 9
9 -7 5 -79 -7 5 -7
2 0 8 02 0 8 0
8 9 -1 -18 9 -1 -1
I get no error, but it is giving the wrong answer.我没有收到错误,但它给出了错误的答案。 Any clue why?
任何线索为什么? Thanks!
谢谢!
def determinant(inputFileName):
def cofactorExp(listOfRows):
if len(listOfRows) <= 2:
return (float(listOfRows[0][0]) * float(listOfRows[1][1])) - (float(listOfRows[0][1]) * float(listOfRows[1][0]))
else:
for i in range(len(listOfRows)):
tempList = listOfRows[:]
del tempList[i]
for x in range(len(tempList)):
tempList[x] = tempList[x][1:]
det = ((-1) ** i) * float(listOfRows[i][0]) * cofactorExp(tempList)
return det
rows = []
for line in open(inputFileName):
rows append(line split(" "))
for item in rows:
if "\n" in item[len(item) - 1]:
item[len(item) - 1] = item[len(item) - 1][:-1]
return(cofactorExp(rows))
A few things一些事情
Your open file command doesnt properly handle spaces before and after the data您的打开文件命令没有正确处理数据前后的空格
rows = []
for line in open(inputFileName):
rows.append(line.split(" "))
for item in rows:
if "\n" in item[len(item) - 1]:
item[len(item) - 1] = item[len(item) - 1][:-1]
when I ran the code on my made up matrix, the command return this当我在我的矩阵上运行代码时,命令返回这个
[['3', '6', '8', '9'], ['9', '-7', '5', '-7'], ['2', '0', '8', '0'], ['8', '9', '-1', '-1', '']]
Notice there is an empty element in the matrix.注意矩阵中有一个空元素。 Dont forget to add periods when calling a command in an object
在对象中调用命令时不要忘记添加句点
I recommend using the example for csv module http://docs.python.org/2/library/csv.html我建议使用 csv 模块http://docs.python.org/2/library/csv.html的示例
return det
seems to prematurely exit the function since the det is in the scope of the loop似乎过早退出函数,因为 det 在循环的范围内
Lastly, there is an easier method to solve and code the determinant最后,有一个更简单的方法来解决和编码行列式
(aei+bfg+cdh)-(ceg+bdi+afh)
http://en.wikipedia.org/wiki/Determinant http://en.wikipedia.org/wiki/Determinant
from numpy import *
x=input("give order of square matrix")
a=[]
for i in range(x):
a.append([])
for j in range(x):
y=raw_input("input a["+str(i)+"]["+ str(j)+ "] element")
a[i].append(y)
b=array(a)
print b
def rem(cc):
s=cc.shape
y=[]
for i in range(s[0]):
y.append([])
for j in range(s[0]):
if i==0:
continue
elif j==x:
continue
else:
y[i].append(cc[i][j])
y.pop(0)
return array(y)
def det(bb):
n=0
s=bb.shape
if s==(1,1):
return bb[0][0]
else:
for j in range(s[0]):
x=j
global x
p=int(bb[0][j])
pp=int(det(rem(bb)))
k=p*pp
n=n+((-1)**(j))*int(k)
return n
print "value is ",det(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.