Explorar o código

Added pretty printing of possibilities with 'add_exponents' as usage example.

Sander Mathijs van Veen %!s(int64=14) %!d(string=hai) anos
pai
achega
fa6beda1e0
Modificáronse 4 ficheiros con 23 adicións e 6 borrados
  1. 12 1
      src/possibilities.py
  2. 1 1
      src/rules/numerics.py
  3. 2 3
      src/rules/poly.py
  4. 8 1
      src/rules/powers.py

+ 12 - 1
src/possibilities.py

@@ -1,3 +1,10 @@
+# Each rule will append its hint message to the following dictionary. The
+# function pointer to the apply function of the rule is used as key. The
+# corresponding value is a string, which will be used to produce the hint
+# message. The string will be processed using string.format().
+MESSAGES = {}
+
+
 class Possibility(object):
     def __init__(self, root, handler, args):
         self.root = root
@@ -5,11 +12,15 @@ class Possibility(object):
         self.args = args
 
     def __str__(self):
+        if self.handler in MESSAGES:
+            return MESSAGES[self.handler].format(self.root, *self.args)
+
         return '<Possibility root="%s" handler=%s args=%s>' \
                 % (self.root, self.handler.func_name, self.args)
 
     def __repr__(self):
-        return str(self)
+        return '<Possibility root="%s" handler=%s args=%s>' \
+                % (self.root, self.handler.func_name, self.args)
 
     # TODO: Add unit tests
     def __eq__(self, other):

+ 1 - 1
src/rules/numerics.py

@@ -1,5 +1,5 @@
 from ..node import ExpressionLeaf as Leaf, OP_DIV, OP_MUL
-from ..possibilities import Possibility as P
+from ..possibilities import Possibility as P, MESSAGES
 from .utils import nary_node
 
 

+ 2 - 3
src/rules/poly.py

@@ -1,8 +1,7 @@
 from itertools import combinations
 
-from ..node import ExpressionNode as Node, ExpressionLeaf as Leaf, \
-        OP_ADD, OP_MUL
-from ..possibilities import Possibility as P
+from ..node import ExpressionNode as Node, OP_ADD, OP_MUL
+from ..possibilities import Possibility as P, MESSAGES
 from .utils import nary_node
 from .numerics import add_numerics
 

+ 8 - 1
src/rules/powers.py

@@ -2,8 +2,9 @@ from itertools import combinations
 
 from ..node import ExpressionNode as N, ExpressionLeaf as L, \
                    OP_NEG, OP_MUL, OP_DIV, OP_POW
-from ..possibilities import Possibility as P
+from ..possibilities import Possibility as P, MESSAGES
 from .utils import nary_node
+from ..translate import _
 
 
 def match_add_exponents(node):
@@ -137,6 +138,12 @@ def add_exponents(root, args):
     return nary_node('*', scope)
 
 
+#MESSAGES[add_exponents] = _('Add the exponents of {1[0]} and {1[1]}, which'
+#        ' will reduce to {1[0][0]}^({1[0][1]} + {1[1][1]}).')
+MESSAGES[add_exponents] = _('Add the exponents of {1} and {2}, which'
+        ' will reduce to {1[0]}^({1[1]} + {2[1]}).')
+
+
 def subtract_exponents(root, args):
     """
     a^p / a^q  ->  a^(p - q)