@@ -27,7 +27,17 @@ class Vec:
27
27
or on the right
28
28
>>> a * 3.0
29
29
Vec(3.0, 6.0, 9.0)
30
+
31
+ and dot product
32
+ >>> a.dot(b)
33
+ 10
34
+
35
+ and printed in vector notation
36
+ >>> print(a)
37
+ <1 2 3>
38
+
30
39
"""
40
+
31
41
def __init__ (self , * v ):
32
42
self .v = list (v )
33
43
@@ -40,8 +50,12 @@ def fromlist(cls, v):
40
50
return inst
41
51
42
52
def __repr__ (self ):
43
- args = ', ' .join (repr (x ) for x in self .v )
44
- return 'Vec({})' .format (args )
53
+ args = ', ' .join ([repr (x ) for x in self .v ])
54
+ return f'{ type (self ).__name__ } ({ args } )'
55
+
56
+ def __str__ (self ):
57
+ components = ' ' .join ([str (x ) for x in self .v ])
58
+ return f'<{ components } >'
45
59
46
60
def __len__ (self ):
47
61
return len (self .v )
@@ -50,22 +64,28 @@ def __getitem__(self, i):
50
64
return self .v [i ]
51
65
52
66
def __add__ (self , other ):
53
- # Element-wise addition
67
+ " Element-wise addition"
54
68
v = [x + y for x , y in zip (self .v , other .v )]
55
69
return Vec .fromlist (v )
56
70
57
71
def __sub__ (self , other ):
58
- # Element-wise subtraction
72
+ " Element-wise subtraction"
59
73
v = [x - y for x , y in zip (self .v , other .v )]
60
74
return Vec .fromlist (v )
61
75
62
76
def __mul__ (self , scalar ):
63
- # Multiply by scalar
77
+ " Multiply by scalar"
64
78
v = [x * scalar for x in self .v ]
65
79
return Vec .fromlist (v )
66
80
67
81
__rmul__ = __mul__
68
82
83
+ def dot (self , other ):
84
+ "Vector dot product"
85
+ if not isinstance (other , Vec ):
86
+ raise TypeError
87
+ return sum (x_i * y_i for (x_i , y_i ) in zip (self , other ))
88
+
69
89
70
90
def test ():
71
91
import doctest
0 commit comments