Minor updates to the vector demo (GH-24853)

This commit is contained in:
Raymond Hettinger 2021-03-15 19:53:58 -07:00 committed by GitHub
parent 0269ce87c9
commit d69ae758a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 25 additions and 5 deletions

View File

@ -27,7 +27,17 @@ class Vec:
or on the right or on the right
>>> a * 3.0 >>> a * 3.0
Vec(3.0, 6.0, 9.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): def __init__(self, *v):
self.v = list(v) self.v = list(v)
@ -40,8 +50,12 @@ class Vec:
return inst return inst
def __repr__(self): def __repr__(self):
args = ', '.join(repr(x) for x in self.v) args = ', '.join([repr(x) for x in self.v])
return 'Vec({})'.format(args) return f'{type(self).__name__}({args})'
def __str__(self):
components = ' '.join([str(x) for x in self.v])
return f'<{components}>'
def __len__(self): def __len__(self):
return len(self.v) return len(self.v)
@ -50,22 +64,28 @@ class Vec:
return self.v[i] return self.v[i]
def __add__(self, other): def __add__(self, other):
# Element-wise addition "Element-wise addition"
v = [x + y for x, y in zip(self.v, other.v)] v = [x + y for x, y in zip(self.v, other.v)]
return Vec.fromlist(v) return Vec.fromlist(v)
def __sub__(self, other): def __sub__(self, other):
# Element-wise subtraction "Element-wise subtraction"
v = [x - y for x, y in zip(self.v, other.v)] v = [x - y for x, y in zip(self.v, other.v)]
return Vec.fromlist(v) return Vec.fromlist(v)
def __mul__(self, scalar): def __mul__(self, scalar):
# Multiply by scalar "Multiply by scalar"
v = [x * scalar for x in self.v] v = [x * scalar for x in self.v]
return Vec.fromlist(v) return Vec.fromlist(v)
__rmul__ = __mul__ __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(): def test():
import doctest import doctest