From c420c67b82b3dfc859cdf4ef0f1752d4373395b6 Mon Sep 17 00:00:00 2001 From: Victor Shnayder Date: Thu, 11 Oct 2012 17:40:26 -0400 Subject: [PATCH] Actually implement exact vs factors-don't-matter comparisons in chemcalc --- common/lib/capa/capa/chem/chemcalc.py | 18 ++++++++++++++---- common/lib/capa/capa/chem/tests.py | 11 +++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/common/lib/capa/capa/chem/chemcalc.py b/common/lib/capa/capa/chem/chemcalc.py index b2198b5537..1df8302b37 100644 --- a/common/lib/capa/capa/chem/chemcalc.py +++ b/common/lib/capa/capa/chem/chemcalc.py @@ -312,12 +312,14 @@ def divide_chemical_expression(s1, s2, ignore_state=False): return Fraction(treedic['1 factors'][0] / treedic['2 factors'][0]) -def chemical_equations_equal(eq1, eq2, ignoreFactor=True): +def chemical_equations_equal(eq1, eq2, exact=False): """ - Check whether two chemical equations are the same. If ignoreFactor is True, - then they are considered equal if they differ by a constant factor. + Check whether two chemical equations are the same. - arrows matter: ->, and <-> are different. + If exact is False, then they are considered equal if they differ by a + constant factor. + + arrows matter: -> and <-> are different. e.g. chemical_equations_equal('H2 + O2 -> H2O2', 'O2 + H2 -> H2O2') -> True @@ -325,6 +327,10 @@ def chemical_equations_equal(eq1, eq2, ignoreFactor=True): chemical_equations_equal('H2 + O2 -> H2O2', 'O2 + H2 <-> H2O2') -> False + chemical_equations_equal('H2 + O2 -> H2O2', '2 H2 + 2 O2 -> 2 H2O2') -> True + chemical_equations_equal('H2 + O2 -> H2O2', '2 H2 + 2 O2 -> 2 H2O2', exact=True) -> False + + If there's a syntax error, we raise pyparsing.ParseException. """ # for now, we do a manual parse for the arrow. @@ -359,4 +365,8 @@ def chemical_equations_equal(eq1, eq2, ignoreFactor=True): # factors don't match (molecule counts to add up) return False + if exact and factor_left != 1: + # want an exact match. + return False + return True diff --git a/common/lib/capa/capa/chem/tests.py b/common/lib/capa/capa/chem/tests.py index 433fe6feea..7f9ceba6e0 100644 --- a/common/lib/capa/capa/chem/tests.py +++ b/common/lib/capa/capa/chem/tests.py @@ -44,7 +44,18 @@ class Test_Compare_Equations(unittest.TestCase): self.assertFalse(chemical_equations_equal('H2 + O2 -> H2O2', 'O2 + H2 <-> 2H2O2')) + def test_exact_match(self): + self.assertTrue(chemical_equations_equal('H2 + O2 -> H2O2', + '2O2 + 2H2 -> 2H2O2')) + self.assertFalse(chemical_equations_equal('H2 + O2 -> H2O2', + '2O2 + 2H2 -> 2H2O2', exact=True)) + + # order still doesn't matter + self.assertTrue(chemical_equations_equal('H2 + O2 -> H2O2', + 'O2 + H2 -> H2O2', exact=True)) + + def test_syntax_errors(self): self.assertRaises(ParseException, chemical_equations_equal, 'H2 + O2 a-> H2O2',