Skip to content

Instantly share code, notes, and snippets.

@bdsaglam
Last active October 23, 2019 12:45
Show Gist options
  • Select an option

  • Save bdsaglam/557f5e6d089a88325829c5627cb59042 to your computer and use it in GitHub Desktop.

Select an option

Save bdsaglam/557f5e6d089a88325829c5627cb59042 to your computer and use it in GitHub Desktop.
A wrapper for dictionaries with numeric values
_numeric_types = (int, float, complex)
class NumericDict(dict):
def __add__(self, other):
if isinstance(other, _numeric_types):
return self.apply(lambda v: v + other)
if isinstance(other, NumericDict):
return self.__class__({k: v + other.get(k, 0) for k, v in self.items()})
raise NotImplementedError()
def __radd__(self, other):
return self + other
def __sub__(self, other):
if isinstance(other, _numeric_types):
return self.apply(lambda v: v - other)
if isinstance(other, NumericDict):
return self.__class__({k: v - other.get(k, 0) for k, v in self.items()})
raise NotImplementedError()
def __rsub__(self, other):
return -self + other
def __mul__(self, other):
if isinstance(other, (int, float)):
return self.apply(lambda v: v * other)
if isinstance(other, NumericDict):
return self.__class__({k: v * other.get(k, 1) for k, v in self.items()})
raise NotImplementedError()
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
if isinstance(other, _numeric_types):
return self.apply(lambda v: v / other)
if isinstance(other, NumericDict):
return self.__class__({k: v / other.get(k, 1) for k, v in self.items()})
raise NotImplementedError()
def __rtruediv__(self, other):
if isinstance(other, _numeric_types):
return self.apply(lambda v: other / v)
raise NotImplementedError()
def __floordiv__(self, other):
if isinstance(other, _numeric_types):
return self.apply(lambda v: v // other)
if isinstance(other, NumericDict):
return self.__class__({k: v // other.get(k, 1) for k, v in self.items()})
raise NotImplementedError()
def __rfloordiv__(self, other):
if isinstance(other, _numeric_types):
return self.apply(lambda v: other // v)
raise NotImplementedError()
def __neg__(self):
return self.__class__({k: -v for k, v in self.items()})
def apply(self, func):
return self.__class__({k: func(v) for k, v in self.items()})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment