In this exercise we will construct a class to represent a mathematical object called the vector. A vector is a list of elements, exactly like a list in Python:
v = [1, 2, 3]
w = [3, 2, 5]
We want to implement the following methods:
__init__(self, elements)Create the __init__ method in your class Vector and use self.elements to store the provided elements parameter as a list.
__mul__(self, other)These objects can be multiplied together in different ways but we will consider only the dot-product:
v * w = 1*3 + 2*2 + 3*5
= 22
We will do this in our method with a list comprehension. Use the following guidelines to implement __mul__ in your class:
A list comprehension looks like:
list_comp = [some_operation(element) for element in list]
Try the following to get a feel for listcomps:
squares = [element ** 2 for element in [1,2,3]]
zip(A, B) will return an element each from A, B as a tuple so in our listcomp:
list_comp = [some_operation(a, b) for a, b in zip(A, B)]
a * b is the operation we want to perform sum(List) will add all of the values of the list togetherrss(self)This stands for Root Sum Square and is essentially the square root of the dot product of self with its self.
Hints:
math module's sqrt__mul____cmp__(self, other)This is the compartor operator where self and other are both Vector instances. We will say that for vectors U, V,
U > V if rss(U) > rss(V)
U < V if rss(U) < rss(V)
U == V if rss(U) == rss(V)
__str__(self)All we want to do here is return a string representation of a list object.
Hint: Apply the function str to something.
Once you have made your Vector class run the test function and make sure all tests pass. The test function has stored values for what it expects to be the result for each of these methods.
In [1]:
import math
# make your class here ...
In [2]:
def test():
p = Vector([1, 2, 3.14])
q = Vector([1, 2, 3.14])
r = Vector(range(3))
tests = ['str(p)', 'str(q)', 'str(r)', 'p * q', 'q * r',\
'p.rss()', 'q.rss()', 'r.rss()', 'p > q', 'p < q', 'p == q', 'q > r', 'q < r', 'q == r']
truths = ['[1, 2, 3.14]', '[1, 2, 3.14]', '[0, 1, 2]',\
14.8596, 8.280000000000001, 3.85481517067, 3.85481517067, 2.2360679775,\
False, False, True, True, False, False]
for truth, test in zip(truths, tests):
eval_result = eval(test)
if type(eval_result) == type(truth):
if (isinstance(truth, float) and eval_result - truth < 1e-8) or (eval_result == truth):
test_result = 'PASSED'
else:
test_result = 'FAILED expected: {}'.format(truth)
else:
test_result = 'FAILED expected type: {} but got {}'.format(type(truth), type(eval_result))
print '{:10} = {:>15}\t{}'.format(test, eval_result, test_result)
In [ ]:
test()