Skip to content

Instantly share code, notes, and snippets.

@garcia
Created January 31, 2015 04:37
Show Gist options
  • Save garcia/498c848daaa64e556f79 to your computer and use it in GitHub Desktop.
Save garcia/498c848daaa64e556f79 to your computer and use it in GitHub Desktop.
Implements a plus-or-minus "operator", +OR-
import itertools
import math
class _OR(object):
def __radd__(self, lhs):
if isinstance(lhs, PlusOrMinus):
copy = PlusOrMinus(*lhs)
else:
copy = PlusOrMinus(lhs)
copy.plusorminus = True
return copy
OR = _OR()
class PlusOrMinus(tuple):
def __new__(cls, *elements):
return super(PlusOrMinus, cls).__new__(cls, elements)
def __init__(self, *elements):
super(PlusOrMinus, self).__init__(*elements)
self.plusorminus = False
def __add__(self, rhs):
if rhs is OR:
return NotImplemented
return PlusOrMinus(*(v+rhs for v in self))
def __sub__(self, rhs):
if self.plusorminus:
return PlusOrMinus(*itertools.chain(*((v+rhs, v-rhs) for v in self)))
else:
return PlusOrMinus(*(v-rhs for v in self))
def __mul__(self, rhs):
return PlusOrMinus(*(v*rhs for v in self))
def __div__(self, rhs):
return PlusOrMinus(*(v/rhs for v in self))
def __mod__(self, rhs):
return PlusOrMinus(*(v%rhs for v in self))
def __pow__(self, rhs):
return PlusOrMinus(*(v**rhs for v in self))
def quadratic_formula(a, b, c):
return (-b +OR- math.sqrt(b**2 - 4*a*c)) / (2*a)
if __name__ == '__main__':
a = 1 +OR- 5
print 'a = 1 +OR- 5 =', a
b = a +OR- 0.5
print 'b = a +OR- 0.5 =', b
c = b + 10
print 'c = b + 10 =', c
x = quadratic_formula(1, 3, -4)
print 'quadratic_formula(1, 3, -4) =', x
# a = 1 +OR- 5 = (6, -4)
# b = a +OR- 0.5 = (6.5, 5.5, -3.5, -4.5)
# c = b + 10 = (16.5, 15.5, 6.5, 5.5)
#
# quadratic_formula(1, 3, -4) = (1.0, -4.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment