-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathvector_v5.py
More file actions
67 lines (50 loc) · 1.67 KB
/
Copy pathvector_v5.py
File metadata and controls
67 lines (50 loc) · 1.67 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
A multi-dimensional ``Vector`` class, take 5
"""
from array import array
import math
import reprlib
import numbers
class Vector:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __len__(self):
return len(self._components)
def __iter__(self):
return iter(self._components)
def __abs__(self):
return math.sqrt(sum(x * x for x in self))
def __eq__(self, other):
return (len(self) == len(other) and
all(a == b for a, b in zip(self, other)))
def __str__(self):
return str(tuple(self))
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('['):-1]
return 'Vector({})'.format(components)
def __getitem__(self, index):
cls = type(self)
if isinstance(index, slice):
return cls(self._components[index])
elif isinstance(index, numbers.Integral):
return self._components[index]
else:
msg = '{cls.__name__} indices must be integers'
raise TypeError(msg.format(cls=cls))
def __mul__(self, scalar):
if isinstance(scalar, numbers.Real):
return Vector(n * scalar for n in self)
else:
return NotImplemented
def __rmul__(self, scalar):
return self * scalar
# ...
def __matmul__(self, other): # Python 3.5 only!
try:
return sum(a * b for a, b in zip(self, other))
except TypeError:
return NotImplemented
def __rmatmul__(self, other):
return self @ other # syntax error if Python < 3.5