Question: Implement a custom SparseMatrix class using a custom CustomHashMap class. A sparse matrix is a type of matrix where most of its elements are zero
Implement a custom SparseMatrix class using a custom CustomHashMap class. A sparse matrix is a type of matrix where most of its elements are zero or have no significant value. Sparse matrices are used in various computational applications to save memory and computational effort, as it is more efficient to store and process only nonzero elements. Use the skeleton code below.
class CustomHashMap:
def initselfsize:
Initializes the hash table with a given size.
:param size: Size of the hash table.
self.size size
self.table Nonesize
def hashselfkey:
Hashes the key to an index in the table.
:param key: The integer key to hash.
:return: An index in the range of the table size.
pass
def setselfkey value:
Sets the value at the hashed index for the given key.
:param key: The integer key.
:param value: The float value to store.
pass
def getselfkey:
Retrieves the value for the given key.
:param key: The integer key to retrieve the value for.
:return: The float value associated with the key, or None if
not found.
pass
def displayself:
Displays the hash table contents.
pass
class SparseMatrix:
def initselfrows cols:
Initializes a sparse matrix using CustomHashMap.
:param rows: Number of rows in the matrix.
:param cols: Number of columns in the matrix.
pass
def getkeyselfrow col:
Generates a unique key for the given row and column.
:param row: Row index.
:param col: Column index.
:return: An integer key.
pass
def setselfrow col, value:
Sets a value in the sparse matrix.
:param row: Row index.
:param col: Column index.
:param value: Float value to set.
pass
def getselfrow col:
Gets a value from the sparse matrix.
:param row: Row index.
:param col: Column index.
:return: Float value at the given position, or None if not
set.
pass
def todenseself:
Converts the sparse matrix to a dense D list
representation.
:return: D list representing the matrix.
pass
def addselfother:
Adds two sparse matrices of the same dimensions.
:param other: SparseMatrix to add.
:return: A new SparseMatrix representing the sum.
pass
def subselfother:
Subtracts another sparse matrix from this one.
:param other: SparseMatrix to subtract.
:return: A new SparseMatrix representing the difference.
pass
def displayself:
Displays the sparse matrix in a readable format.
pass
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
