sort.py 839 B

12345678910111213141516171819202122232425262728293031323334353637
  1. from itertools import product, combinations
  2. from ..node import Scope, OP_ADD, OP_MUL
  3. from ..possibilities import Possibility as P, MESSAGES
  4. from ..translate import _
  5. def match_sort_multiplicants(node):
  6. """
  7. Sort multiplicant factors by swapping
  8. x * 2 -> 2x
  9. """
  10. assert node.is_op(OP_MUL)
  11. p = []
  12. scope = Scope(node)
  13. for i, n in enumerate(scope[1:]):
  14. left_nb = scope[i]
  15. if n.is_numeric() and not left_nb.is_numeric():
  16. p.append(P(node, move_constant, (scope, n, left_nb)))
  17. return p
  18. def move_constant(root, args):
  19. scope, constant, destination = args
  20. scope.replace(destination, constant * destination)
  21. scope.remove(constant)
  22. return scope.as_nary_node()
  23. MESSAGES[move_constant] = \
  24. _('Move constant {2} to the left of the multiplication {0}.')