Search for question
Question

5. (10 pts) Implement a vector class that supports two types of vectors: normal or dense vectors

represented using lists and sparse vectors represented using dictionaries.

For normal or dense vectors, you can represent them with a list. However, for sparse vectors

where many elements are zero, using a list is inefficient. Instead, we will use a dictionary where

the keys represent the indices of non-zero values, and the corresponding values represent the

value of the vector at that index. Hence, the vector [2, 4, 6] can be stored as a list: [2, 4, 6] or

as a dictionary (0:2, 1:4, 2:6).

a) Write a function that adds two (dense) vectors. (1 pts)

b) Write a function that adds two sparse vectors. (1 pts)

c) Write a function that adds a sparse vector and a dense vector. (1 pts)

However, this is a bit clumsy to use in practice. Really, we would like to represent sparse and

dense vectors as classes, this way we can overload operators such as +(__add_) and get

sensible output. For example, using + on two dense vectors implemented as lists would append

the second vector to the first, instead of adding the two together. Implement sparse and dense

vectors. Both classes should have the following capabilities:

d) Print vector. (1 pts)

e) Add two vectors. Overload the + operator (__add_) to perform element-wise addition of

two vectors. If the other vector is a Sparse Vector, the addition should consider the zero

elements and add the non-zero elements to the resulting vector. If the other vector is a

Dense Vector, the addition should be performed accordingly. (3 pts)

f) Multiply two vectors. Overload the operator (mul_) to perform element-wise

multiplication of two vectors. If the other vector is a Sparse Vector, the multiplication

should consider the zero elements and return a vector with zero values where the

corresponding indices are not present. If the other vector is a Dense Vector, the

multiplication should be performed accordingly. (3 pts)

Fig: 1