【发布时间】:2013-11-25 05:44:28
【问题描述】:
Python 3 中的以下代码旨在返回任何阶矩阵的行列式。它接受一个文本文件,格式为:
3 6 8 9
9 -7 5 -7
2 0 8 0
8 9 -1 -1
我没有收到错误,但它给出了错误的答案。任何线索为什么?谢谢!
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))
【问题讨论】:
-
你可以使用 numpy 来完成这个任务,除非这是一个家庭作业:stackoverflow.com/questions/462500/…
-
手工计算,看看你的函数的计算从哪里开始不同。
-
这是一个家庭作业,但我们被允许编写我们想要的代码。不过我不能用那个。
标签: python matrix determinants