curriculum/challenges/english/blocks/learn-special-methods-by-building-a-vector-space/65fc899d77495504d6deeccc.md
The scalar product between two vectors $\mathbf{a}$ and $\mathbf{b}$ is indicated as:
\( \mathbf{a} \cdot \mathbf{b} = a_1 \cdot b_1 + a_2 \cdot b_2 + \ldots + a_n \cdot b_n = \sum_{i=1}^{n} a_i \cdot b_i \)
Where each component of $\mathbf{a}$ is multiplied by the correspondent component of $\mathbf{b}$, and all the products are summed together, resulting in a number.
Within the elif clause, implement the above formula to compute the result of a scalar product and return the result. Remember that your implementation must be valid for any vector, independently from the number of components, when the method is inherited.
You should implement the scalar product calculation and return the result inside the elif body of your __mul__ method.
({ test: () => assert(runPython(`
v1 = R2Vector(x=2, y=3)
v2 = R2Vector(x=0.5, y=1.25)
v3 = R3Vector(x=2, y=3, z=1.5)
v4 = R3Vector(x=0.5, y=1.25, z=1.5)
v1*v2 == 4.75 and v3*v4 == 7.0
`)) })
class R2Vector:
def __init__(self, *, x, y):
self.x = x
self.y = y
def norm(self):
return sum(val**2 for val in vars(self).values())**0.5
def __str__(self):
return str(tuple(getattr(self, i) for i in vars(self)))
def __repr__(self):
arg_list = [f'{key}={val}' for key, val in vars(self).items()]
args = ', '.join(arg_list)
return f'{self.__class__.__name__}({args})'
def __add__(self, other):
if type(self) != type(other):
return NotImplemented
kwargs = {i: getattr(self, i) + getattr(other, i) for i in vars(self)}
return self.__class__(**kwargs)
def __sub__(self, other):
if type(self) != type(other):
return NotImplemented
kwargs = {i: getattr(self, i) - getattr(other, i) for i in vars(self)}
return self.__class__(**kwargs)
--fcc-editable-region--
def __mul__(self, other):
if type(other) in (int, float):
kwargs = {i: getattr(self, i) * other for i in vars(self)}
return self.__class__(**kwargs)
elif type(self) == type(other):
pass
--fcc-editable-region--
class R3Vector(R2Vector):
def __init__(self, *, x, y, z):
super().__init__(x=x, y=y)
self.z = z
v1 = R2Vector(x=2, y=3)
v2 = R2Vector(x=0.5, y=1.25)
print(f'v1 = {v1}')
print(f'v2 = {v2}')
v3 = v1 + v2
print(f'v1 + v2 = {v3}')
v4 = v1 - v2
print(f'v1 - v2 = {v4}')