1
0

Finalize vector.py

This commit is contained in:
2024-01-13 13:53:21 +01:00
parent 15fb2d096e
commit 71f6c19f51
3 changed files with 57 additions and 63 deletions

View File

@ -114,9 +114,9 @@ class Matrix:
if isinstance(other, Matrix):
if self.__shape__ != other.__shape__:
raise ValueError("The shape of the operands must be the same")
return self.__data__ + other.__data__
return Matrix(self.__data__ + other.__data__)
elif isinstance(other, int) or isinstance(other, float):
return self.__data__ + other
return Matrix(self.__data__ + other)
else:
raise ValueError("Only a number or another ``Matrix`` can be added to a ``Matrix``")
@ -145,7 +145,7 @@ class Matrix:
def __truediv__(self, other):
if isinstance(other, int) or isinstance(other, float):
return self.__data__ / other
return Matrix(self.__data__ / other)
else:
raise ValueError("A ``Matrix`` can only be divided ba a number")
@ -172,4 +172,3 @@ class Matrix:
def __setitem__(self, key, value):
self.__data__[key] = value

View File

@ -4,65 +4,34 @@ from matrix import Matrix
class Vector(Matrix):
__data__ = []
def __init__(self, data):
def __init__(self, data: list | int):
"""
:type data: list | int
"""
super().__init__(numpy.array([0])) # TODO: remove in future
if isinstance(data, list):
self.__data__ = data
super().__init__(data, (len(data), 1))
elif isinstance(data, int):
self.__init__([0] * data)
else:
raise ValueError("data must be a list or an integer for dimension")
def get_data(self):
return self.__data__
def get_dimension(self):
return len(self.__data__)
def __iter__(self):
return iter(self.__data__)
def __eq__(self, other):
return self.__data__ == other.__data__
def __str__(self):
return f"{self.__data__}"
def __neg__(self):
return Vector([-x for x in self.__data__])
def __add__(self, other):
if isinstance(other, Vector):
if self.get_dimension() != other.get_dimension():
raise ValueError("The vectors to be added must have the same dimension")
return Vector([(x + y) for (x, y) in zip(self, other)])
elif isinstance(other, int) or isinstance(other, float):
return Vector([(x + other) for x in self.__data__])
else:
raise ValueError("A vector can only be multiplied with an vector (dot product) or a scalar")
def __radd__(self, other):
return self + other
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
return super().shape()[0]
def __mul__(self, other):
if isinstance(other, Vector):
return sum([(x * y) for (x, y) in zip(self, other)])
return (super().transpose().__mul__(other))[0][0]
elif isinstance(other, int) or isinstance(other, float):
return Vector([(other * x) for x in self.__data__])
return super().__mul__(other)
else:
raise ValueError("A vector can only be multiplied with an vector (dot product) or a scalar")
def __rmul__(self, other):
return self * other
def norm(self, **kwargs):
return super().norm()
def normalize(self):
return self / self.norm()