class SparseMatrix:
def __init__(self, rows, cols):
"""
Initialize the sparse matrix.
:param rows: Total number of rows.
:param cols: Total number of columns.
"""
self.rows = rows
self.cols = cols
# We use a dictionary to store only non-zero values.
# Format: {(row, col): value}
self._data = {}
def __str__(self):
"""
Return a string representation of the non-zero elements.
"""
if not self._data:
return "Empty Sparse Matrix (all zeros)"
string_repr = ""
for (r, c), val in sorted(self._data.items()):
string_repr += f"({r}, {c}) -> {val}\n"
return string_repr.strip()
def insert(self, row, col, value):
"""
Insert or update a value in the matrix.
"""
# 1. Check bounds
if row >= self.rows or col >= self.cols or row < 0 or col < 0:
raise IndexError("Index out of bounds.")
# 2. If value is 0, we ensure it is NOT stored.
# If the key exists and we are setting it to 0, we remove the key.
if value == 0:
if (row, col) in self._data:
del self._data[(row, col)]
return
# 3. Store non-zero value
self._data[(row, col)] = value
def get(self, row, col):
"""
Retrieve a value. Returns 0 if the key doesn't exist.
"""
if row >= self.rows or col >= self.cols or row < 0 or col < 0:
raise IndexError("Index out of bounds.")
# Return the value if found, otherwise return 0
return self._data.get((row, col), 0)
def add(self, other_matrix):
"""
Add another sparse matrix to this one.
Returns a new SparseMatrix.
"""
if self.rows != other_matrix.rows or self.cols != other_matrix.cols:
raise ValueError("Matrices must have the same dimensions to add.")
# Create a new matrix for the result
result = SparseMatrix(self.rows, self.cols)
# Helper to add two values (handling the implicit zeros)
def add_values(r, c):
val1 = self.get(r, c)
val2 = other_matrix.get(r, c)
return val1 + val2
# We need to check all indices that exist in EITHER matrix
# Create a set of all coordinates present in both matrices
all_coords = set(self._data.keys()) | set(other_matrix._data.keys())
for r, c in all_coords:
sum_val = add_values(r, c)
if sum_val != 0:
result.insert(r, c, sum_val)
return result
def to_dense(self):
"""
Convert to a standard 2D list (for visualization/verification).
Warning: Can consume a lot of memory if matrix is huge.
"""
matrix = [[0] * self.cols for _ in range(self.rows)]
for (r, c), val in self._data.items():
matrix[r][c] = val
return matrix
# --- Usage Example ---
if __name__ == "__main__":
print("--- Creating Matrix A (5x5) ---")
matA = SparseMatrix(5, 5)
# Insert some non-zero values
matA.insert(0, 0, 10)
matA.insert(1, 2, 20)
matA.insert(3, 4, 30)
print("Sparse Representation of A:")
print(matA)
print("\nRetrieving specific values:")
print(f"Value at (0,0): {matA.get(0, 0)}") # Should be 10
print(f"Value at (0,1): {matA.get(0, 1)}") # Should be 0 (implicit)
print("\n--- Creating Matrix B (5x5) ---")
matB = SparseMatrix(5, 5)
matB.insert(1, 2, 5) # Overlap with A
matB.insert(3, 4, -30) # Will cancel out A
matB.insert(4, 4, 99) # Unique to B
print("Sparse Representation of B:")
print(matB)
print("\n--- Adding A + B ---")
matC = matA.add(matB)
print("Resulting Sparse Representation:")
print(matC)
print("\n--- Visualizing Result as Dense Matrix ---")
dense_version = matC.to_dense()
for row in dense_version:
print(row)