+++ /dev/null
-class Vec:\r
- """ A simple vector class\r
-\r
- Instances of the Vec class can be constructed from numbers\r
-\r
- >>> a = Vec(1, 2, 3)\r
- >>> b = Vec(3, 2, 1)\r
-\r
- added\r
- >>> a + b\r
- Vec(4, 4, 4)\r
-\r
- subtracted\r
- >>> a - b\r
- Vec(-2, 0, 2)\r
-\r
- and multiplied by a scalar on the left\r
- >>> 3.0 * a\r
- Vec(3.0, 6.0, 9.0)\r
-\r
- or on the right\r
- >>> a * 3.0\r
- Vec(3.0, 6.0, 9.0)\r
- """\r
- def __init__(self, *v):\r
- self.v = list(v)\r
-\r
- @classmethod\r
- def fromlist(cls, v):\r
- if not isinstance(v, list):\r
- raise TypeError\r
- inst = cls()\r
- inst.v = v\r
- return inst\r
-\r
- def __repr__(self):\r
- args = ', '.join(repr(x) for x in self.v)\r
- return 'Vec({0})'.format(args)\r
-\r
- def __len__(self):\r
- return len(self.v)\r
-\r
- def __getitem__(self, i):\r
- return self.v[i]\r
-\r
- def __add__(self, other):\r
- # Element-wise addition\r
- v = [x + y for x, y in zip(self.v, other.v)]\r
- return Vec.fromlist(v)\r
-\r
- def __sub__(self, other):\r
- # Element-wise subtraction\r
- v = [x - y for x, y in zip(self.v, other.v)]\r
- return Vec.fromlist(v)\r
-\r
- def __mul__(self, scalar):\r
- # Multiply by scalar\r
- v = [x * scalar for x in self.v]\r
- return Vec.fromlist(v)\r
-\r
- __rmul__ = __mul__\r
-\r
-\r
-def test():\r
- import doctest\r
- doctest.testmod()\r
-\r
-test()\r