fork download
  1. from collections import namedtuple
  2. from functools import partial
  3. from itertools import starmap
  4. import operator
  5.  
  6. class Vector:
  7. def _lift_un(self, op):
  8. """apply unary operator"""
  9. return map(op, self)
  10.  
  11. def _lift_bi(self, op, v):
  12. """apply binary operator"""
  13. return starmap(op, zip(self, v))
  14.  
  15. def __mul__(self, s):
  16. return type(self)(*self._lift_un(partial(operator.mul, s)))
  17.  
  18. __rmul__ = __mul__
  19.  
  20. def __neg__(self):
  21. return type(self)(*self._lift_un(operator.neg))
  22.  
  23. def __pos__(self):
  24. return type(self)(*self._lift_un(operator.pos))
  25.  
  26. def __abs__(self):
  27. return sum(self._lift_un(lambda x: x**2))**.5
  28.  
  29. def __add__(self, v):
  30. return type(self)(*self._lift_bi(operator.add, v))
  31.  
  32. __radd__ = __add__
  33.  
  34. def __sub__(self, v):
  35. return type(self)(*self._lift_bi(operator.sub, v))
  36.  
  37. def __eq__(self, v):
  38. return all(self._lift_bi(operator.eq, v))
  39.  
  40. def __ne__(self, v):
  41. return any(self._lift_bi(operator.ne, v))
  42.  
  43. def __repr__(self):
  44. return '%s(%s)' % (type(self).__name__,
  45. ', '.join(self._lift_un(repr)))
  46.  
  47. class Vector3(Vector, namedtuple('_Vector3', 'x y z')):
  48. pass
  49.  
  50. vector = Vector3(0, 0, 0)
  51.  
  52. print vector
  53. print vector + Vector3(1,1,1)
  54. print vector * 5
  55. print abs(vector)
  56. print (vector - Vector3(1,2,3)) * 2 == Vector3(-2,-4,-6)
Success #stdin #stdout 0.11s 8856KB
stdin
Standard input is empty
stdout
Vector3(0, 0, 0)
Vector3(1, 1, 1)
Vector3(0, 0, 0)
0.0
True