-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path033_problem.py
More file actions
66 lines (55 loc) · 2.01 KB
/
033_problem.py
File metadata and controls
66 lines (55 loc) · 2.01 KB
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
#find the determinant of a matrix
def determinant(matrix):
if len(matrix) != len(matrix[0]):
raise ValueError("Matrix must be square")
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for j in range(n):
sub_matrix = [row[:j] + row[j+1:] for row in matrix[1:]]
det += ((-1) ** j) * matrix[0][j] * determinant(sub_matrix)
return det
# Get input for the matrix
size = int(input("Enter the size of the square matrix: "))
matrix = []
print("Enter the elements of the matrix:")
for i in range(size):
row = list(map(int, input().split()))
matrix.append(row)
# Calculate the determinant and print the result
try:
result = determinant(matrix)
print("The determinant of the matrix is:", result)
except ValueError as e:
print(e)
#Logic for interview
def determinant(matrix):
if len(matrix) != len(matrix[0]):
raise ValueError("Matrix must be square")
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for j in range(n):
sub_matrix = [row[:j] + row[j+1:] for row in matrix[1:]]
det += ((-1) ** j) * matrix[0][j] * determinant(sub_matrix)
return det
# Get input for the matrix
size = int(input("Enter the size of the square matrix: "))
matrix = []
print("Enter the elements of the matrix:")
for i in range(size):
row = list(map(int, input().split()))
matrix.append(row)
# Calculate the determinant and print the result
try:
result = determinant(matrix)
print("The determinant of the matrix is:", result)
except ValueError as e:
print(e)
#time complexity: O(n!) in the worst case, because we are calculating the determinant using recursion and the number of operations grows factorially with the size of the matrix. The space complexity is O(n) due to the recursive call stack.