curriculum/challenges/english/blocks/learn-special-methods-by-building-a-vector-space/65f9bc10a9fb1612e066e9e8.md
When adding two vectors, each component of one vector is added to the same component of the other vector. For example, adding (1, 2) and (2, 4) generates a third vector (3, 6), where 3 is the sum of 1 and 2 and 6 is the sum of 2 and 4.
The kwargs dictionary will contain the key-value pairs needed to instantiate a new vector of the same class of the two vectors added together.
Turn the empty dictionary into a dictionary comprehension that iterates through vars(self) and for each key (i) creates a key-value pair, where the key is the same key of the current iteration and its value is the sum of the values of the i attributes of the two operands.
You should turn the empty dictionary assigned to kwargs into a dictionary comprehension that iterates over vars(self).
({
test: () => assert(runPython(`
_Node(_code).find_class("R2Vector").find_function("__add__").find_variable("kwargs").find_comp_iters()[0].is_equivalent("vars(self)")
`))
})
The dictionary comprehension assigned to kwargs should use the variable i to iterate over vars(self).
({
test: () => assert(runPython(`
_Node(_code).find_class("R2Vector").find_function("__add__").find_variable("kwargs").find_comp_targets()[0].is_equivalent("i")
`))
})
The dictionary comprehension assigned to kwargs should use i as the key.
({
test: () => assert(runPython(`
_Node(_code).find_class("R2Vector").find_function("__add__").find_variable("kwargs").find_comp_key().is_equivalent("i")
`))
})
The dictionary comprehension assigned to kwargs should assign the sum of the i attribute of self and the i attribute of other to the i key for each i in vars(self). Use the getattr() function for that.
({ test: () => assert(runPython(`
node = _Node(_code).find_class("R2Vector").find_function("__add__").find_variable("kwargs").find_comp_expr()
node.is_equivalent("getattr(self, i) + getattr(other, i)") or node.is_equivalent("getattr(other, i) + getattr(self, i)")
`)) })
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})'
--fcc-editable-region--
def __add__(self, other):
if type(self) != type(other):
return NotImplemented
kwargs = {}
--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 = R3Vector(x=2, y=2, z=3)
print(f'v1 = {v1}')
print(f'v2 = {v2}')