Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 20 additions & 14 deletions linear_algebra/src/rank_of_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,35 +54,41 @@
1
>>> rank_of_matrix([[]])
0
>>> rank_of_matrix([]) # ✅ new: completely empty matrix
0
>>> m = [[1, 2], [3, 4]]
>>> rank_of_matrix(m) # ✅ new: original matrix should not be modified
2
>>> m # should remain unchanged
[[1, 2], [3, 4]]
"""

rows = len(matrix)
columns = len(matrix[0])
import copy

if not matrix or not matrix[0]:
return 0

A = copy.deepcopy(matrix)

Check failure on line 71 in linear_algebra/src/rank_of_matrix.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N806)

linear_algebra/src/rank_of_matrix.py:71:5: N806 Variable `A` in function should be lowercase
rows, columns = len(A), len(A[0])
rank = min(rows, columns)

for row in range(rank):
# Check if diagonal element is not zero
if matrix[row][row] != 0:
# Eliminate all the elements below the diagonal
if A[row][row] != 0:
for col in range(row + 1, rows):
multiplier = matrix[col][row] / matrix[row][row]
multiplier = A[col][row] / A[row][row]
for i in range(row, columns):
matrix[col][i] -= multiplier * matrix[row][i]
A[col][i] -= multiplier * A[row][i]
else:
# Find a non-zero diagonal element to swap rows
reduce = True
for i in range(row + 1, rows):
if matrix[i][row] != 0:
matrix[row], matrix[i] = matrix[i], matrix[row]
if A[i][row] != 0:
A[row], A[i] = A[i], A[row]
reduce = False
break
if reduce:
rank -= 1
for i in range(rows):
matrix[i][row] = matrix[i][rank]

# Reduce the row pointer by one to stay on the same row
row -= 1
A[i][row] = A[i][rank]

return rank

Expand Down
Loading