This class represents a vector of arbitrary size. You need to give the vector components. Overview of the methods: __init__(components: Collection[float] | None): init the vector __len__(): gets the size of the vector (number of components) __str__(): returns a
| 28 | |
| 29 | |
| 30 | class Vector: |
| 31 | """ |
| 32 | This class represents a vector of arbitrary size. |
| 33 | You need to give the vector components. |
| 34 | |
| 35 | Overview of the methods: |
| 36 | |
| 37 | __init__(components: Collection[float] | None): init the vector |
| 38 | __len__(): gets the size of the vector (number of components) |
| 39 | __str__(): returns a string representation |
| 40 | __add__(other: Vector): vector addition |
| 41 | __sub__(other: Vector): vector subtraction |
| 42 | __mul__(other: float): scalar multiplication |
| 43 | __mul__(other: Vector): dot product |
| 44 | copy(): copies this vector and returns it |
| 45 | component(i): gets the i-th component (0-indexed) |
| 46 | change_component(pos: int, value: float): changes specified component |
| 47 | euclidean_length(): returns the euclidean length of the vector |
| 48 | angle(other: Vector, deg: bool): returns the angle between two vectors |
| 49 | """ |
| 50 | |
| 51 | def __init__(self, components: Collection[float] | None = None) -> None: |
| 52 | """ |
| 53 | input: components or nothing |
| 54 | simple constructor for init the vector |
| 55 | """ |
| 56 | if components is None: |
| 57 | components = [] |
| 58 | self.__components = list(components) |
| 59 | |
| 60 | def __len__(self) -> int: |
| 61 | """ |
| 62 | returns the size of the vector |
| 63 | """ |
| 64 | return len(self.__components) |
| 65 | |
| 66 | def __str__(self) -> str: |
| 67 | """ |
| 68 | returns a string representation of the vector |
| 69 | """ |
| 70 | return "(" + ",".join(map(str, self.__components)) + ")" |
| 71 | |
| 72 | def __add__(self, other: Vector) -> Vector: |
| 73 | """ |
| 74 | input: other vector |
| 75 | assumes: other vector has the same size |
| 76 | returns a new vector that represents the sum. |
| 77 | """ |
| 78 | size = len(self) |
| 79 | if size == len(other): |
| 80 | result = [self.__components[i] + other.component(i) for i in range(size)] |
| 81 | return Vector(result) |
| 82 | else: |
| 83 | raise Exception("must have the same size") |
| 84 | |
| 85 | def __sub__(self, other: Vector) -> Vector: |
| 86 | """ |
| 87 | input: other vector |
no outgoing calls