-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathvector.py
More file actions
48 lines (37 loc) · 1.81 KB
/
vector.py
File metadata and controls
48 lines (37 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Vector:
def __init__(self, components):
self.components = components
def __str__(self):
return "(" + ", ".join(map(str, self.components)) + ")"
def __len__(self):
return len(self.components)
def __getitem__(self, index):
return self.components[index]
def __setitem__(self, index, value):
self.components[index] = value
def __add__(self, other):
if len(self) != len(other):
raise ValueError("Vectors must have the same dimension for addition.")
result_components = [x + y for x, y in zip(self.components, other.components)]
return Vector(result_components)
def __sub__(self, other):
if len(self) != len(other):
raise ValueError("Vectors must have the same dimension for subtraction.")
result_components = [x - y for x, y in zip(self.components, other.components)]
return Vector(result_components)
def __mul__(self, scalar):
result_components = [x * scalar for x in self.components]
return Vector(result_components)
def dot(self, other):
if len(self) != len(other):
raise ValueError("Vectors must have the same dimension for dot product.")
return sum(x * y for x, y in zip(self.components, other.components))
def cross(self, other):
if len(self) != 3 or len(other) != 3:
raise ValueError("Cross product is defined for 3-dimensional vectors only.")
result_components = [
self.components[1] * other.components[2] - self.components[2] * other.components[1],
self.components[2] * other.components[0] - self.components[0] * other.components[2],
self.components[0] * other.components[1] - self.components[1] * other.components[0]
]
return Vector(result_components)