Skip to content

Commit

Permalink
Merge pull request #67 from jwfoley/solution-arithmetic
Browse files Browse the repository at this point in the history
added Solution.__sub__ and Solution.__truediv__
  • Loading branch information
lewisamarshall committed Jan 2, 2017
2 parents 7afb988 + e338b57 commit 9f8cd02
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions ionize/Solution/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,23 @@ def __add__(self, other):

__radd__ = __add__

def __sub__(self, other):
if isinstance(other, Solution):
ions = list(set(self.ions + other.ions))
return Solution(ions, [self.concentration(ion) -
other.concentration(ion)
for ion in ions]
)
else:
try:
ion, concentration = other
new_contents = dict(self._contents)
new_contents[ion] = self.concentration(ion) - concentration
return Solution(new_contents.keys(), new_contents.values())
except:
raise TypeError('Solutions add to other Solutions or to an'
'(Ion, concentration) iterable pair.')

def __mul__(self, other):
if other >= 0:
return Solution(self.ions,
Expand All @@ -203,6 +220,13 @@ def __mul__(self, other):

__rmul__ = __mul__

def __truediv__(self, other):
if other > 0:
return Solution(self.ions,
[c / other for c in self.concentrations])
else:
raise TypeError

def __str__(self):
"""Return a string representing the Solution."""
return "Solution(pH={:.3g}, I={:.3g} M)".format(self.pH,
Expand Down

0 comments on commit 9f8cd02

Please sign in to comment.