Skip to content

Commit

Permalink
Merge pull request #19 from JvgRansika/add-sub-and-cross-product
Browse files Browse the repository at this point in the history
add __sub__ and __rmul__
  • Loading branch information
jv-ransika authored Jan 6, 2024
2 parents fa07bfe + 4ef462b commit 66c3b2a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
15 changes: 11 additions & 4 deletions pymathzone/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,15 @@ def __add__(self, other):
:return: vector
"""
if isinstance(other, Vector):
pass
return Vector(addition(self, other))
else:
raise ValueError("Invalid addition!")

return Vector(addition(self, other))
def __sub__(self, other):
if isinstance(other, Vector):
return self.__add__(-1 * other)
else:
raise ValueError("Invalid subtraction!")

def __eq__(self, other):
if not isinstance(other, Vector):
Expand All @@ -57,14 +61,17 @@ def __mul__(self, other):
else:
raise Exception("Invalid multiplication")

def __rmul__(self, other):
return self.__mul__(other)


def dot(self, other):
if isinstance(other, int) or isinstance(other, float):
return self.__mul__(other)
elif isinstance(other, Vector):
return dot_multiplication_with_vector(self,other)
return dot_multiplication_with_vector(self, other)
else:
raise Exception("Invalid dot product")


def get_dimension(self):
return len(self.components)
20 changes: 20 additions & 0 deletions tests/test_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,26 @@ def test_add_negative_vector(self):
result = v1 + v2
self.assertEqual(result.components, (0, 0, 0))

# subtraction
def test_subtraction_with_vector(self):
vector1 = Vector((5, 3))
vector2 = Vector((2, 1))
result = vector1 - vector2
expected = Vector((3, 2))
self.assertEqual(result, expected)

def test_subtraction_with_scalar(self):
vector = Vector((4, 2))
with self.assertRaises(ValueError) as context:
vector - 5
self.assertEqual(str(context.exception), "Invalid subtraction!")

def test_subtraction_with_invalid_type(self):
vector = Vector((1, 2))
with self.assertRaises(ValueError) as context:
vector - "hello"
self.assertEqual(str(context.exception), "Invalid subtraction!")

def test_multiplication_with_scalar(self):
vector = Vector((2, 3))
result = vector * 2
Expand Down

0 comments on commit 66c3b2a

Please sign in to comment.