Vector Operations

Implement a class Vector that represents a mathematical vector in 2D space. The class should have methods for vector addition, subtraction, dot product, and cross product.

Example 1:

 
Input: 
v1 = Vector(1, 2) 
v2 = Vector(2, 3) 
print(v1.add(v2)) 
print(v1.subtract(v2)) 
print(v1.dot(v2)) 
print(v1.cross(v2)) 

Output: 
Vector(3, 5) 
Vector(-1, -1) 
8 
-1

In 2D space, the dot product of vectors (a, b) and (c, d) is (ac + bd) and the cross product is (ad – bc).

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Vector({self.x}, {self.y})"

    def add(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def subtract(self, other):
        return Vector(self.x - other.x, self.y - other.y)

    def dot(self, other):
        return self.x * other.x + self.y * other.y

    def cross(self, other):
        return self.x * other.y - self.y * other.x

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!