|
| 1 | +""" |
| 2 | +Implement a `Vector3D` class, which represents a 3D vector. |
| 3 | +
|
| 4 | +You have to implement these for this class: |
| 5 | +- `__init__` magic function, which receives `x`, `y`, `z` and sets `self.x`, |
| 6 | + `self.y`, `self.z` accordingly. |
| 7 | +
|
| 8 | +>>> v = Vector3D(1, 2, 3) |
| 9 | +>>> v.x |
| 10 | +1 |
| 11 | +>>> v.y |
| 12 | +2 |
| 13 | +>>> v.z |
| 14 | +3 |
| 15 | +
|
| 16 | +- `to_tuple()` method, which converts the vector to a tuple in `(x, y, z)` |
| 17 | + format. |
| 18 | +
|
| 19 | +>>> v.to_tuple() |
| 20 | +(1, 2, 3) |
| 21 | +
|
| 22 | +- `norm()` method, which calculates the norm (length) of the vector. The norm |
| 23 | + can be calculated using sqrt(x^2 + y^2 + z^2). |
| 24 | +
|
| 25 | +>>> v.norm() ** 2 |
| 26 | +14.0 |
| 27 | +
|
| 28 | +- Addition between instances of `Vector3D`. The addition follows usual |
| 29 | + component-wise addition rule. |
| 30 | +
|
| 31 | +>>> w = Vector3D(4, 5, 6) |
| 32 | +>>> u = v + w |
| 33 | +>>> u.to_tuple() |
| 34 | +(5, 7, 9) |
| 35 | +
|
| 36 | +- Substraction between instances of `Vector3D`. The Substraction also follows |
| 37 | + usual component-wise substraction rule. |
| 38 | +
|
| 39 | +>>> s = v - w |
| 40 | +>>> s.to_tuple() |
| 41 | +(-3, -3, -3) |
| 42 | +
|
| 43 | +- Scalar multiplication of vector. `s * v`, where `s` is a number and `v` is an |
| 44 | + instance of `Vector3D` gives an instance of `Vector3D` where its `x`, `y`, `z` |
| 45 | + components are multiplied by `s`. |
| 46 | +
|
| 47 | +>>> t = 3 * v |
| 48 | +>>> t.to_tuple() |
| 49 | +(3, 6, 9) |
| 50 | +""" |
| 51 | +import math |
| 52 | + |
| 53 | + |
| 54 | +class Vector3D: |
| 55 | + def __init__(self, x, y, z): |
| 56 | + self.x = x |
| 57 | + self.y = y |
| 58 | + self.z = z |
| 59 | + |
| 60 | + def norm(self): |
| 61 | + return math.sqrt(self.x**2 + self.y**2 + self.z**2) |
| 62 | + |
| 63 | + def to_tuple(self): |
| 64 | + return (self.x, self.y, self.z) |
| 65 | + |
| 66 | + def __add__(self, rhs): |
| 67 | + return Vector3D(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) |
| 68 | + |
| 69 | + def __sub__(self, rhs): |
| 70 | + return Vector3D(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) |
| 71 | + |
| 72 | + def __rmul__(self, scalar): |
| 73 | + return Vector3D(scalar * self.x, scalar * self.y, scalar * self.z) |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + import doctest |
| 78 | + |
| 79 | + doctest.testmod(verbose=True) |
0 commit comments