-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindDeterminant.py
70 lines (58 loc) · 2.02 KB
/
FindDeterminant.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
## FindDeterminant.py
## Elliot Treble
## 7/09/19
import random
'''
Find determinant of an n*n matrix
'''
print("Hello World")
def FindDet(matrix):
print("-------------------------NEW MATRIX----------------------------")
print(matrix)
for row in matrix:
if len(row) != len(matrix):
print("matrix must be square")
return -1
return RecursiveHelper(matrix)
def RecursiveHelper(matrix):
print("length of current matrix is ")
print(len(matrix))
if len(matrix) == 2:
print(matrix)
print("2 x 2 matrix has determinant ")
print(matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0])
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] ###base case
else:
result = 0
for col in range(0, len(matrix)):
print("iterating for column " + str(col) + " current matrix is " + str(matrix))
result += matrix[0][col]*((-1)**col)*RecursiveHelper(BuildSubMatrix(matrix, col)) ## sum alternating sign of sub matrices
print("last result is " + str(result))
return result
def BuildSubMatrix(matrix, col):
newMatrix = []
for row in matrix[1:]:
newRow = row.copy()
print("removing " + str(newRow.pop(col)) + " from row " + str(row))
print("new row is " + str(newRow))
print("old row is " + str(row))
print(newRow)
newMatrix.append(newRow)
print("new subMatrix is ")
print(newMatrix)
return newMatrix
def rdmSquareMatrixGenerator():
##randomize size of matrix
print("GENERATING RANDOM MATRIX")
size = random.randint(0,7)
newMatrix = []
for i in range(0, size):
newRow = []
for i in range(0, size):
##populate rows with random values
newRow.append(random.randint(0,10))
newMatrix.append(newRow)
print("Matrix Generated")
print(newMatrix)
return newMatrix
print(FindDet(rdmSquareMatrixGenerator()))