Created
May 1, 2021 21:54
-
-
Save Auax/da4d612b094e0962b54778082c23ecd5 to your computer and use it in GitHub Desktop.
Codewars Vector Class (Exercice)
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
| # The code could be resolved with a "combine" function but I'm lazy to change it. | |
| from math import sqrt | |
| class Vector: | |
| """ | |
| Vector main class | |
| """ | |
| def __init__(self, vector:list): | |
| self.vector = vector | |
| def __str__(self): | |
| return f"({','.join(map(str, self.vector))})" | |
| def __len__(self): | |
| return len(self.vector) | |
| def __iter__(self): | |
| return iter(self.vector) | |
| def __list__(self): | |
| return list(self.vector) | |
| def __getitem__(self, i): | |
| return self.vector[i] | |
| def __eq__(self, other): | |
| if not isinstance(other, Vector): | |
| # don't attempt to compare against unrelated types | |
| return NotImplemented | |
| return self.vector == list(other) | |
| def is_same_len(func): # Raise error if vector length is not the same (exercice rule) | |
| def wrapper(self, other): | |
| if len(self) != len(other): | |
| raise Exception("Vectors must be the same length!") | |
| return func(self,other) | |
| return wrapper | |
| @is_same_len | |
| def add(self, vector): | |
| func = lambda x: x[0] + x[1] | |
| return Vector(list(map(func, zip(self.vector, vector)))) | |
| @is_same_len | |
| def subtract(self, vector): | |
| func = lambda x: x[0] - x[1] | |
| return Vector(list(map(func, zip(self.vector, vector)))) | |
| @is_same_len | |
| def dot(self, vector): | |
| func = lambda x: x[0] * x[1] | |
| return sum(list(map(func, zip(self.vector, vector)))) | |
| def norm(self): | |
| func = lambda x: x ** 2 | |
| return sqrt(sum(list(map(func, self.vector)))) | |
| def equals(self, vector): | |
| return self.vector == list(vector) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment