| 1 |
class Vec: |
| 2 |
""" A simple vector class |
| 3 |
|
| 4 |
Instances of the Vec class can be constructed from numbers |
| 5 |
|
| 6 |
>>> a = Vec(1, 2, 3) |
| 7 |
>>> b = Vec(3, 2, 1) |
| 8 |
|
| 9 |
added |
| 10 |
>>> a + b |
| 11 |
Vec(4, 4, 4) |
| 12 |
|
| 13 |
subtracted |
| 14 |
>>> a - b |
| 15 |
Vec(-2, 0, 2) |
| 16 |
|
| 17 |
and multiplied by a scalar on the left |
| 18 |
>>> 3.0 * a |
| 19 |
Vec(3.0, 6.0, 9.0) |
| 20 |
|
| 21 |
or on the right |
| 22 |
>>> a * 3.0 |
| 23 |
Vec(3.0, 6.0, 9.0) |
| 24 |
""" |
| 25 |
def __init__(self, *v): |
| 26 |
self.v = list(v) |
| 27 |
|
| 28 |
@classmethod |
| 29 |
def fromlist(cls, v): |
| 30 |
if not isinstance(v, list): |
| 31 |
raise TypeError |
| 32 |
inst = cls() |
| 33 |
inst.v = v |
| 34 |
return inst |
| 35 |
|
| 36 |
def __repr__(self): |
| 37 |
args = ', '.join(repr(x) for x in self.v) |
| 38 |
return 'Vec({0})'.format(args) |
| 39 |
|
| 40 |
def __len__(self): |
| 41 |
return len(self.v) |
| 42 |
|
| 43 |
def __getitem__(self, i): |
| 44 |
return self.v[i] |
| 45 |
|
| 46 |
def __add__(self, other): |
| 47 |
|
| 48 |
v = [x + y for x, y in zip(self.v, other.v)] |
| 49 |
return Vec.fromlist(v) |
| 50 |
|
| 51 |
def __sub__(self, other): |
| 52 |
|
| 53 |
v = [x - y for x, y in zip(self.v, other.v)] |
| 54 |
return Vec.fromlist(v) |
| 55 |
|
| 56 |
def __mul__(self, scalar): |
| 57 |
|
| 58 |
v = [x * scalar for x in self.v] |
| 59 |
return Vec.fromlist(v) |
| 60 |
|
| 61 |
__rmul__ = __mul__ |
| 62 |
|
| 63 |
|
| 64 |
def test(): |
| 65 |
import doctest |
| 66 |
doctest.testmod() |
| 67 |
|
| 68 |
test() |