【问题标题】:Recursive Matrix determinant function?递归矩阵行列式函数?
【发布时间】:2015-05-25 22:10:28
【问题描述】:
def determinant(M):
    """
    Finds the determinant of matrix M.
    """
    if dimension(M)[0]!=dimension(M)[1]:
        print("This matrix is not a square matrix and therefore cannot have a determinant!")
        return
    elif dimension(M)[0]==dimension(M)[1]:
        if dimension(M)==(2,2):
            return (M[0][0]*M[1][1])-(M[0][1]*M[1][0])
        else:
            return (M[0][0]*determinant(reduce_matrix(M,1,1))) - (M[0][1]*determinant(reduce_matrix(M,1,2))) + (M[0][2]*determinant(reduce_matrix(M,1,3)))

编辑:这里的代码能够找到 3x3 矩阵的行列式,但只能找到 3x3 矩阵。如何编辑它以找到任何大小的方阵的行列式?

【问题讨论】:

  • 您要返回什么数据类型?如何确定 M 中的列数?我猜,什么是 M - 一个列表列表?
  • 最终结果将是一个整数,它是您最初开始使用的任何矩阵的行列式。 M 是列表的列表,如 [[1,2,3],[4,5,6],[7,8,9]]。 M 中的列数为维度(M)[1]。此外,reduce_matrix 是一个预先编写的函数(reduce_matrix(M,i,j)),它从矩阵 M 中删除第 i 行和第 j 列。
  • 您是在问如何计算具有 indeterminate 列数的矩阵的行列式吗?
  • 有点,是的。列数取决于您输入的矩阵。

标签: python loops python-3.x for-loop recursion


【解决方案1】:

您可以使用列表推导通过输入列表应用表达式,如下所示:

[n ** 2 for n in [1, 2, 3]] == [1, 4, 9]

我假设您想累积结果,在这种情况下您可以使用sum 函数。

sum([1, 2, 3]) == 6

通过应用两者,您最终会得到如下表达式:

sum([((-1) ** i) * (M[0][i] * determinant(reduce_matrix(M, 1, i + 1))) for i in range(0, dimension(M)[1])])

请注意,range 不包括最后一个元素。

还要注意运算符的优先级:

-1 ** 2 != (-1) ** 2

【讨论】:

    猜你喜欢
    • 2018-03-14
    • 1970-01-01
    • 2020-03-11
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2018-11-27
    • 2021-04-10
    相关资源
    最近更新 更多