implements the constructor of the following class and the sparseness_metric method. Notice that the constructor should: - set the value of self.shape to the size of the matrix m. If m is None the size must be (0,0) - fill the dictionary self.rows as a dictionary of dictionaries with the non-0 values of m. You will need to iterate through the entire array m for this Example of execution (image) def SparseMatrix2(m=None, **kwargs): import itertools def add_to_dict(d, key1, key2, val): <... YOUR CODE HERE ...> return d class SparseMatrix2_class: def __init__(self, m=m, **kwargs): self.rows = {} self.shape = ... <... YOUR CODE HERE ...> def sparseness_metric(self): metric = <... YOUR CODE HERE ...> return metric return SparseMatrix2_class(**kwargs) manually check your code with: import numpy as np def random_sparse_matrix(size): m = np.random.randint(2, size=size) m = m * np.random.randint(10,size=size) return m m = random_sparse_matrix((5,3)) sm = SparseMatrix2(m) print(m.shape, sm.sparseness_metric()) m s = SparseMatrix2(m) print("rows", s.rows) print("length of each row", [len(s.rows[i]) for i in list(s.rows.keys())]) s = SparseMatrix2(None) s.shape
implements the constructor of the following class and the sparseness_metric method. Notice that the constructor should:
- set the value of self.shape to the size of the matrix m. If m is None the size must be (0,0)
- fill the dictionary self.rows as a dictionary of dictionaries with the non-0 values of m. You will need to iterate through the entire array m for this
Example of execution (image)
def SparseMatrix2(m=None, **kwargs):
import itertools
def add_to_dict(d, key1, key2, val):
<... YOUR CODE HERE ...>
return d
class SparseMatrix2_class:
def __init__(self, m=m, **kwargs):
self.rows = {}
self.shape = ...
<... YOUR CODE HERE ...>
def sparseness_metric(self):
metric = <... YOUR CODE HERE ...>
return metric
return SparseMatrix2_class(**kwargs)
manually check your code with:
import numpy as np
def random_sparse_matrix(size):
m = np.random.randint(2, size=size)
m = m * np.random.randint(10,size=size)
return m
m = random_sparse_matrix((5,3))
sm = SparseMatrix2(m)
print(m.shape, sm.sparseness_metric())
m
s = SparseMatrix2(m)
print("rows", s.rows)
print("length of each row", [len(s.rows[i]) for i in list(s.rows.keys())])
s = SparseMatrix2(None)
s.shape
Step by step
Solved in 4 steps with 3 images