def rm_l_c(n,c,a,AC): #function to remove line and column
for i in range(0,n-1): #row loop
for j in range(0,n-1): #colum
k = j+1
if (j<c):k=j; #the first element in index 0,0
AC[i][j]=a[i+1][k] #The error is here
a=[[1,2,3],[4,5,6],[7,8,9]]
detA=0
AC=[]
def det(a,n):
if(n==2):
detA=a[0][0]*a[1][1]-a[0][1]*a[1][0]
else:
for c in range(0,n):
rm_l_c(n,c,a,AC)
n = n-1
detA=detA+((-1)**c)*a[0][c]*det(AC,n)
return detA
det(a,3)
这段代码是使用拉普拉斯展开实现行列式的
https://en.wikipedia.org/wiki/Laplace_expansion
问题出在AC[i][j]=a[i+1][k]
我不知道该怎么做
当我试着运行它的时候,它也给出了这个错误
Traceback (most recent call last):
File "C:\Users\zerocool\Desktop\det.py", line 22, in <module>
det(a,3)
File "C:\Users\zerocool\Desktop\det.py", line 17, in det
rm_l_c(n,c,a,AC)
File "C:\Users\zerocool\Desktop\det.py", line 6, in rm_l_c
AC[i][j]=a[i+1][k]
IndexError: list index out of range
>>>
作为胡安帕.阿里维拉加您不能在空列表中插入元素。 由于您只在rm\u l\c中修改AC,因此每次以正确的大小运行rm\u l\c时,您都可以通过执行以下操作来创建AC,其中包含空元素(或您希望默认为空的任何其他元素)。你知道吗
您也可以通过使用列表理解来获得rm\u l\c的相同最终结果,列表理解更像python,更易于阅读。你知道吗
相关问题 更多 >
编程相关推荐