- if coefficients is not None:
- for symbol, coefficient in coefficients:
- if isinstance(symbol, Expression) and symbol.issymbol():
- symbol = str(symbol)
- elif not isinstance(symbol, str):
- raise TypeError('symbols must be strings')
- if not isinstance(coefficient, numbers.Rational):
- raise TypeError('coefficients must be rational numbers')
- if coefficient != 0:
- self._coefficients[symbol] = coefficient
+ if coefficients is None:
+ return Constant(constant)
+ coefficients = [(symbol, coefficient)
+ for symbol, coefficient in coefficients if coefficient != 0]
+ if len(coefficients) == 0:
+ return Constant(constant)
+ elif len(coefficients) == 1 and constant == 0:
+ symbol, coefficient = coefficients[0]
+ if coefficient == 1:
+ return Symbol(symbol)
+ self = object().__new__(cls)
+ self._coefficients = {}
+ for symbol, coefficient in coefficients:
+ if isinstance(symbol, Symbol):
+ symbol = str(symbol)
+ elif not isinstance(symbol, str):
+ raise TypeError('symbols must be strings or Symbol instances')
+ if isinstance(coefficient, Constant):
+ coefficient = coefficient.constant
+ if not isinstance(coefficient, numbers.Rational):
+ raise TypeError('coefficients must be rational numbers or Constant instances')
+ self._coefficients[symbol] = coefficient
+ if isinstance(constant, Constant):
+ constant = constant.constant