Last active
November 15, 2021 12:46
-
-
Save victor-iyi/8abc832475e1fbc07413232cff3f9579 to your computer and use it in GitHub Desktop.
A light weight vector utility class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Generic | |
| from typing import Iterable | |
| from typing import TypeVar | |
| # Generic type. | |
| T = TypeVar('T') | |
| class Vector(Generic[T]): | |
| """A light-weight Vector utility class, used to perform various operations | |
| on vectors. | |
| Parameters: | |
| v: list | |
| List of numbers to be used as vector. | |
| Example: | |
| ```python | |
| >>> a = Vector(1, 2, 3) | |
| >>> b = Vector(4, 5, 6) | |
| >>> len(a) | |
| 3 | |
| >>> # Vector addition. | |
| >>> a + b | |
| Vector(1, 2, 4) | |
| >>> # Vector subtraction. | |
| >>> a - b | |
| Vector(-3, -3, -3) | |
| >>> # Scalar multiplication. | |
| >>> 2 * a | |
| Vector(2, 4, 6) | |
| >>> # Creating from a list. | |
| >>> d = Vector.fromlist([7, 8, 9, 10]) | |
| >>> e = Vector(11, 12, 13, 14) | |
| >>> # Vector dot product. | |
| >>> d.dot(e) | |
| 430 | |
| ``` | |
| Methods: | |
| # Vector list. | |
| def __init__(self, *v) | |
| # Object representation. | |
| def __repr__(self) | |
| # String representation. | |
| def __str__(self) | |
| # Length of a vector. | |
| def __len__(self) | |
| # Get item by index. | |
| def __getitem__(self, i) | |
| def __add__(self, other) | |
| # Vectors addition. | |
| def __sub__(self, other) | |
| # Vector subtraction. | |
| def __mul__(self, scalar) | |
| # Scalar multiplication. | |
| __rmul__ = __mul__ | |
| # Vector multiplication. | |
| def multiply(self, vec): | |
| @classmethod | |
| def fromlist(cls, l): | |
| Attributes: | |
| v - list | |
| Reference to the vector list. | |
| """ | |
| def __init__(self, *v: Iterable[T]) -> None: | |
| # Vector list. | |
| self.v = v | |
| def __repr__(self) -> str: | |
| # Object representation. | |
| args = ', '.join(map(repr, self.v)) | |
| return f'{type(self).__name__}({args})' | |
| def __str__(self) -> str: | |
| # String representation. | |
| return f'{self.v}' | |
| def __len__(self) -> int: | |
| # Length of a vector. | |
| return len(self.v) | |
| def __getitem__(self, i: int) -> T: | |
| # Get item by index. | |
| return self.v[i] | |
| def __add__(self, other: object) -> 'Vector': | |
| if isinstance(other, Vector): | |
| # Vectors addition. | |
| v = [x + y for x, y in zip(self.v, other.v)] | |
| return Vector.fromlist(v) | |
| else: | |
| return NotImplemented | |
| def __sub__(self, other: object) -> 'Vector': | |
| if isinstance(other, Vector): | |
| # Vector subtraction. | |
| v = [x - y for x, y in zip(self.v, other.v)] | |
| return Vector.fromlist(v) | |
| else: | |
| return NotImplemented | |
| def __mul__(self, scalar: T) -> 'Vector': | |
| # Scalar multiplication. | |
| v = [x * scalar for x in self.v] | |
| return Vector.fromlist(v) | |
| # Right multiplication should do the scalar multiplication | |
| __rmul__ = __mul__ | |
| @classmethod | |
| def fromlist(cls, l: list[T]) -> 'Vector': | |
| """ | |
| Create a Vector object from a list. | |
| :params | |
| l: list | |
| The list of numbers to be converted. | |
| :raise | |
| TypeError - | |
| Expected {type(list)}; Given {type(v)} | |
| :return inst | |
| A vector object. Instance of the Vector class. | |
| """ | |
| if type(l) is not list: | |
| raise TypeError(f'"Expected {type(list)}; Given {type(l)}') | |
| inst = cls(*l) | |
| return inst | |
| def dot(self, vec: object) -> T: | |
| """ | |
| Dot product of a Vector. | |
| :params | |
| v: <obj Vector> | |
| Vector to multiply by current vector. | |
| :raise | |
| TypeError - | |
| Expected {type(self)}; Given {type(vec)} | |
| :return int | |
| Result from the multiplication operation. | |
| """ | |
| if type(vec) is not type(self): | |
| raise TypeError(f'Expected {type(self)}; Given {type(vec)}') | |
| result = [x * y for x, y in zip(self.v, vec.v)] | |
| return sum(result) | |
| if __name__ == '__main__': | |
| a: Vector[int] = Vector(1, 2, 3) | |
| b: Vector[int] = Vector(4, 5, 6) | |
| print(f'{a = }') | |
| print(f'{b = }') | |
| print(f'\n{len(a) = }') | |
| print(f'{a[0] = }') | |
| print('\na + b =', a + b) | |
| print('a - b =', a - b) | |
| print('a * b =', a * b) | |
| c: Vector[str] = Vector('a', 'b', 'b', 'd') | |
| d: Vector[str] = Vector.fromlist(['e', 'f', 'g', 'h']) | |
| print(f'{len(c) = }') | |
| print(f'{c + d = }') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment