import numbers
import re
+from collections import OrderedDict
from fractions import Fraction, gcd
raise TypeError('coefficients must be rational numbers '
'or Constant instances')
self._coefficients[symbol] = coefficient
+ self._coefficients = OrderedDict(sorted(self._coefficients.items()))
if isinstance(constant, Constant):
constant = constant.constant
if not isinstance(constant, numbers.Rational):
raise TypeError('constant must be a rational number '
'or a Constant instance')
self._constant = constant
- self._symbols = tuple(sorted(self._coefficients))
+ self._symbols = tuple(self._coefficients)
self._dimension = len(self._symbols)
return self
__getitem__ = coefficient
def coefficients(self):
- for symbol in self.symbols:
- yield symbol, self.coefficient(symbol)
+ yield from self._coefficients.items()
@property
def constant(self):
return Gt(self, other)
def __hash__(self):
- return hash((tuple(sorted(self._coefficients.items())), self._constant))
+ return hash((tuple(self.coefficients()), self._constant))
def _toint(self):
lcm = functools.reduce(lambda a, b: a*b // gcd(a, b),
return left / right
raise SyntaxError('invalid syntax')
+ _RE_NUM_VAR = re.compile(r'(\d+|\))\s*([^\W\d_]\w*|\()')
+
@classmethod
def fromstring(cls, string):
- string = re.sub(r'(\d+|\))\s*([^\W\d_]\w*|\()', r'\1*\2', string)
+ # add implicit multiplication operators, e.g. '5x' -> '5*x'
+ string = cls._RE_NUM_VAR.sub(r'\1*\2', string)
tree = ast.parse(string, 'eval')
return cls._fromast(tree)