Skip to content

Commit d69ae75

Browse files
authored
Minor updates to the vector demo (GH-24853)
1 parent 0269ce8 commit d69ae75

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

Tools/demo/vector.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,17 @@ class Vec:
2727
or on the right
2828
>>> a * 3.0
2929
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+
3039
"""
40+
3141
def __init__(self, *v):
3242
self.v = list(v)
3343

@@ -40,8 +50,12 @@ def fromlist(cls, v):
4050
return inst
4151

4252
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}>'
4559

4660
def __len__(self):
4761
return len(self.v)
@@ -50,22 +64,28 @@ def __getitem__(self, i):
5064
return self.v[i]
5165

5266
def __add__(self, other):
53-
# Element-wise addition
67+
"Element-wise addition"
5468
v = [x + y for x, y in zip(self.v, other.v)]
5569
return Vec.fromlist(v)
5670

5771
def __sub__(self, other):
58-
# Element-wise subtraction
72+
"Element-wise subtraction"
5973
v = [x - y for x, y in zip(self.v, other.v)]
6074
return Vec.fromlist(v)
6175

6276
def __mul__(self, scalar):
63-
# Multiply by scalar
77+
"Multiply by scalar"
6478
v = [x * scalar for x in self.v]
6579
return Vec.fromlist(v)
6680

6781
__rmul__ = __mul__
6882

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+
6989

7090
def test():
7191
import doctest

0 commit comments

Comments
 (0)