Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor updates to the vector demo #24853

Merged
merged 3 commits into from
Mar 16, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions Tools/demo/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -40,8 +50,12 @@ def fromlist(cls, v):
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)
Expand All @@ -50,22 +64,28 @@ def __getitem__(self, i):
return self.v[i]

def __add__(self, other):
# Element-wise addition
"Element-wise addition"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't best practise triple quotes for docstrings? Ref. PEP 8/documentation-strings

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're somewhat loose about this. The original rationale was that it would save you from retyping the quotes if the docstring grew to multiple lines. That isn't a likely possibility here.

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
Expand Down