Skip to content

Commit 7c37f5b

Browse files
author
jignesh
committed
solved a small bug
1 parent a71618f commit 7c37f5b

1 file changed

Lines changed: 19 additions & 14 deletions

File tree

linear_algebra/src/rank_of_matrix.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -54,35 +54,40 @@ def rank_of_matrix(matrix: list[list[int | float]]) -> int:
5454
1
5555
>>> rank_of_matrix([[]])
5656
0
57+
>>> rank_of_matrix([]) # ✅ new: completely empty matrix
58+
0
59+
>>> m = [[1, 2], [3, 4]]
60+
>>> rank_of_matrix(m) # ✅ new: original matrix should not be modified
61+
2
62+
>>> m # should remain unchanged
63+
[[1, 2], [3, 4]]
5764
"""
5865

59-
rows = len(matrix)
60-
columns = len(matrix[0])
66+
import copy
67+
if not matrix or not matrix[0]:
68+
return 0
69+
70+
A = copy.deepcopy(matrix)
71+
rows, columns = len(A), len(A[0])
6172
rank = min(rows, columns)
6273

6374
for row in range(rank):
64-
# Check if diagonal element is not zero
65-
if matrix[row][row] != 0:
66-
# Eliminate all the elements below the diagonal
75+
if A[row][row] != 0:
6776
for col in range(row + 1, rows):
68-
multiplier = matrix[col][row] / matrix[row][row]
77+
multiplier = A[col][row] / A[row][row]
6978
for i in range(row, columns):
70-
matrix[col][i] -= multiplier * matrix[row][i]
79+
A[col][i] -= multiplier * A[row][i]
7180
else:
72-
# Find a non-zero diagonal element to swap rows
7381
reduce = True
7482
for i in range(row + 1, rows):
75-
if matrix[i][row] != 0:
76-
matrix[row], matrix[i] = matrix[i], matrix[row]
83+
if A[i][row] != 0:
84+
A[row], A[i] = A[i], A[row]
7785
reduce = False
7886
break
7987
if reduce:
8088
rank -= 1
8189
for i in range(rows):
82-
matrix[i][row] = matrix[i][rank]
83-
84-
# Reduce the row pointer by one to stay on the same row
85-
row -= 1
90+
A[i][row] = A[i][rank]
8691

8792
return rank
8893

0 commit comments

Comments
 (0)