summaryrefslogtreecommitdiffstats
path: root/Tools/demo
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2021-03-16 02:53:58 (GMT)
committerGitHub <noreply@github.com>2021-03-16 02:53:58 (GMT)
commitd69ae758a0606c142c305123dcbad3e3e42d664f (patch)
tree7d85128e404fabace8cf1757325bf6cb733b74f4 /Tools/demo
parent0269ce87c9347542c54a653dd78b9f60bb9fa822 (diff)
downloadcpython-d69ae758a0606c142c305123dcbad3e3e42d664f.zip
cpython-d69ae758a0606c142c305123dcbad3e3e42d664f.tar.gz
cpython-d69ae758a0606c142c305123dcbad3e3e42d664f.tar.bz2
Minor updates to the vector demo (GH-24853)
Diffstat (limited to 'Tools/demo')
-rwxr-xr-xTools/demo/vector.py30
1 files changed, 25 insertions, 5 deletions
diff --git a/Tools/demo/vector.py b/Tools/demo/vector.py
index da5b389..6df1f50 100755
--- a/Tools/demo/vector.py
+++ b/Tools/demo/vector.py
@@ -27,7 +27,17 @@ class Vec:
or on the right
>>> a * 3.0
Vec(3.0, 6.0, 9.0)
+
+ and dot product
+ >>> a.dot(b)
+ 10
+
+ and printed in vector notation
+ >>> print(a)
+ <1 2 3>
+
"""
+
def __init__(self, *v):
self.v = list(v)
@@ -40,8 +50,12 @@ class Vec:
return inst
def __repr__(self):
- args = ', '.join(repr(x) for x in self.v)
- return 'Vec({})'.format(args)
+ args = ', '.join([repr(x) for x in self.v])
+ return f'{type(self).__name__}({args})'
+
+ def __str__(self):
+ components = ' '.join([str(x) for x in self.v])
+ return f'<{components}>'
def __len__(self):
return len(self.v)
@@ -50,22 +64,28 @@ class Vec:
return self.v[i]
def __add__(self, other):
- # Element-wise addition
+ "Element-wise addition"
v = [x + y for x, y in zip(self.v, other.v)]
return Vec.fromlist(v)
def __sub__(self, other):
- # Element-wise subtraction
+ "Element-wise subtraction"
v = [x - y for x, y in zip(self.v, other.v)]
return Vec.fromlist(v)
def __mul__(self, scalar):
- # Multiply by scalar
+ "Multiply by scalar"
v = [x * scalar for x in self.v]
return Vec.fromlist(v)
__rmul__ = __mul__
+ def dot(self, other):
+ "Vector dot product"
+ if not isinstance(other, Vec):
+ raise TypeError
+ return sum(x_i * y_i for (x_i, y_i) in zip(self, other))
+
def test():
import doctest