You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.3 KiB

  1. """ A trivial immutable array that supports basic arithmetic operations.
  2. >>> a = SimpleArray((1.0, 2.0, 3.0))
  3. >>> b = SimpleArray((4.0, 5.0, 6.0))
  4. >>> t = (4.0, 5.0, 6.0)
  5. >>> +a
  6. SimpleArray((1.0, 2.0, 3.0))
  7. >>> -a
  8. SimpleArray((-1.0, -2.0, -3.0))
  9. >>> a + b
  10. SimpleArray((5.0, 7.0, 9.0))
  11. >>> b + a
  12. SimpleArray((5.0, 7.0, 9.0))
  13. >>> a + t
  14. SimpleArray((5.0, 7.0, 9.0))
  15. >>> t + a
  16. SimpleArray((5.0, 7.0, 9.0))
  17. >>> a - b
  18. SimpleArray((-3.0, -3.0, -3.0))
  19. >>> a - t
  20. SimpleArray((-3.0, -3.0, -3.0))
  21. >>> t - a
  22. SimpleArray((3.0, 3.0, 3.0))
  23. >>> a * b
  24. SimpleArray((4.0, 10.0, 18.0))
  25. >>> b * a
  26. SimpleArray((4.0, 10.0, 18.0))
  27. >>> a * t
  28. SimpleArray((4.0, 10.0, 18.0))
  29. >>> t * a
  30. SimpleArray((4.0, 10.0, 18.0))
  31. >>> a / b
  32. SimpleArray((0.25, 0.4, 0.5))
  33. >>> b / a
  34. SimpleArray((4.0, 2.5, 2.0))
  35. >>> a / t
  36. SimpleArray((0.25, 0.4, 0.5))
  37. >>> t / a
  38. SimpleArray((4.0, 2.5, 2.0))
  39. """
  40. import operator
  41. __all__ = ['SimpleArray']
  42. class SimpleArray(tuple):
  43. def _op(self, op, other):
  44. if isinstance(other, tuple):
  45. if len(other) != len(self):
  46. raise TypeError("tuples must have same length for %s" % op)
  47. return SimpleArray(map(op, self, other))
  48. return NotImplemented
  49. def __add__(self, other):
  50. return self._op(operator.add, other)
  51. __radd__ = __add__
  52. def __pos__(self):
  53. return SimpleArray(map(operator.pos, self))
  54. def __neg__(self):
  55. return SimpleArray(map(operator.neg, self))
  56. def __sub__(self, other):
  57. return self._op(operator.sub, other)
  58. def __rsub__(self, other):
  59. return SimpleArray(other)._op(operator.sub, self)
  60. def __mul__(self, other):
  61. return self._op(operator.mul, other)
  62. __rmul__ = __mul__
  63. def __div__(self, other):
  64. return self._op(operator.div, other)
  65. def __floordiv__(self, other):
  66. return self._op(operator.floordiv, other)
  67. def __truediv__(self, other):
  68. return self._op(operator.truediv, other)
  69. def __rdiv__(self, other):
  70. return SimpleArray(other)._op(operator.div, self)
  71. def __rfloordiv__(self, other):
  72. return SimpleArray(other)._op(operator.floordiv, self)
  73. def __rtruediv__(self, other):
  74. return SimpleArray(other)._op(operator.truediv, self)
  75. def __repr__(self):
  76. return "SimpleArray(%s)" % tuple.__repr__(self)
  77. if __name__ == '__main__':
  78. import doctest
  79. doctest.testmod()