Back to Freecodecamp

Step 20

curriculum/challenges/english/blocks/learn-special-methods-by-building-a-vector-space/65f4535bbdb28d436ff3ddc9.md

latest1.4 KB
Original Source

--description--

As you can see from the output, __dict__ contains the values of your instance attributes. Instead of explicitly adding the squares of self.x and self.y, you are going to iterate over the values stored in __dict__ to calculate the value of the norm.

Within the norm method body, replace the content of the parentheses with a generator expression that elevates each value val in self.__dict__.values() to the power of 2. Also, pass that generator expression as the argument to the sum function, so that all the squares are added together before calculating the square root.

--hints--

You should return sum(val**2 for val in self.__dict__.values())**0.5 from norm() method.

js
({ test: () => assert(runPython(`_Node(_code).find_class("R2Vector").find_function("norm").has_return("sum(val**2 for val in self.__dict__.values())**0.5")`)) })

--seed--

--seed-contents--

py

class R2Vector:
    def __init__(self, *, x, y):
        self.x = x
        self.y = y
--fcc-editable-region--
    def norm(self):
        return (self.x**2 + self.y**2)**0.5
--fcc-editable-region--        
    def __str__(self):
        return f'{self.x, self.y}'

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(v1.__dict__)
print(v2.__dict__)