2017-12-20 18:27:00 by wst
数学知识回过头来再看数学,课本上讲的每一个解题步骤不都是一个算法吗?
突然发现自己学了那么多算法,可是仔细想来,自己又能实现几个呢?
正好在复习行列式,顺便实现下:
# -*- coding:utf-8 -*-
import math
__author__ = "alan.wan"
__email__ = "movingheart000@gmail.com"
def get_son_matrix(df, i, j):
""" Generate matrix that remove line i and column j
:param df: original matrix
:param i: line number
:param j: column number
:return: new matrix
"""
l = len(df)
new_list = [[0 for x in range(l-1)] for y in range(l-1)]
for index in range(l):
for column in range(l):
if index < i and column < j:
new_list[index][column] = df[index][column]
elif index > i and column < j:
new_list[index-1][column] = df[index][column]
elif index > i and column > j:
new_list[index-1][column-1] = df[index][column]
elif index < i and column > j:
new_list[index][column-1] = df[index][column]
return new_list
def calculate_det(df, n=0):
"""Calculate determinant of df
:param df: input matrix
:param n: calculate by line n
:return: results
"""
cl = len(df)
if cl == 2:
return df[0][0] * df[1][1] - df[1][0] * df[0][1]
s = 0
for tl in range(cl):
temp_df = get_son_matrix(df, n, tl)
s += df[n][tl] * math.pow(-1, n+tl+2) * calculate_det(temp_df)
return s
if __name__ == "__main__":
df = [
[5, 3, -1, 2, 0],
[1, 7, 2, 5, 2],
[0, -2, 3, 1, 0],
[0, -4, -1, 4, 0],
[0, 2, 3, 5, 0]
]
print calculate_det(df)