|
| 1 | +class Vector: |
| 2 | + """ |
| 3 | + Constructor |
| 4 | +
|
| 5 | + self: a reference to the object we are creating |
| 6 | + vals: a list of integers which are the contents of our vector |
| 7 | + """ |
| 8 | + |
| 9 | + def __init__(self, vals): |
| 10 | + self.vals = vals |
| 11 | + # print("Assigned values ", vals, " to vector.") |
| 12 | + |
| 13 | + """ |
| 14 | + String Function |
| 15 | +
|
| 16 | + Converts the object to a string in readable format for programmers |
| 17 | + """ |
| 18 | + |
| 19 | + def __str__(self): |
| 20 | + return str(self.vals) |
| 21 | + |
| 22 | + def __pow__(self, power): |
| 23 | + return Vector([i ** power for i in self.vals]) |
| 24 | + |
| 25 | + # Calculates Euclidean norm |
| 26 | + def norm(self): |
| 27 | + return sum((self ** 2).vals) ** 0.5 |
| 28 | + |
| 29 | + # __lt__: implements the less than operator (<) |
| 30 | + def __lt__(self, other): |
| 31 | + return self.norm() < other.norm() |
| 32 | + |
| 33 | + # __gt__: implements the greater than operator (>) |
| 34 | + def __gt__(self, other): |
| 35 | + return self.norm() > other.norm() |
| 36 | + |
| 37 | + # __le__: implements the less than equal to operator (<=) |
| 38 | + def __le__(self, other): |
| 39 | + return self.norm() <= other.norm() |
| 40 | + |
| 41 | + # __ge__: implements the greater than equal to operator (>=) |
| 42 | + def __ge__(self, other): |
| 43 | + return self.norm() >= other.norm() |
| 44 | + |
| 45 | + # __eq__: implements the equals operator (==) |
| 46 | + def __eq__(self, other): |
| 47 | + return self.norm() == other.norm() |
| 48 | + |
| 49 | + # __ne__:implements the not equals operator (!=) |
| 50 | + def __ne__(self, other): |
| 51 | + return self.norm() != other.norm() |
| 52 | + |
| 53 | + |
| 54 | +vec = Vector([2, 3, 2]) |
| 55 | +vec2 = Vector([3, 4, 5]) |
| 56 | +print(vec < vec2) # True |
| 57 | +print(vec > vec2) # False |
| 58 | + |
| 59 | +print(vec <= vec2) # True |
| 60 | +print(vec >= vec2) # False |
| 61 | +print(vec <= vec) # True |
| 62 | +print(vec >= vec) # True |
| 63 | + |
| 64 | +print(vec == vec2) # False |
| 65 | +print(vec == vec) # True |
| 66 | + |
| 67 | +print(vec != vec2) # True |
| 68 | +print(vec != vec) # False |
0 commit comments