def __init__(self, monomials = ()): # combine monomials with the same variables and exponents # and bring them into canonical order assert isinstance(monomials, tuple) # create for each monomial a dictionary # with key being the variables and exponents # and value being the coefficient listOfVarsCoeffDicts = [ { monomial.getVars() : monomial.getCoefficient() } for monomial in monomials] # combine the dictionaries using sum combinedVarsCoeffDict = basicAlgorithms.combineDicts( listOfVarsCoeffDicts, _operatorTypePolicy) # turn dictionary into a list of pairs (vars, coefficient) # in canonical order orderedTupleOfVarsCoeffPairs = ( basicAlgorithms.dictToOrderedTupleOfPairs(combinedVarsCoeffDict)) # turn pairs into monomials, skip trivial monomials combinedMonomials = [ Monomial(coefficient, vars) for vars, coefficient in orderedTupleOfVarsCoeffPairs if _coefficientIsNonTrivial(coefficient)] # convert to tuple self._monomials = tuple(combinedMonomials)
def __mul__(self, other): assert isinstance(other, Monomial) # Compute coefficient coefficient = _operatorTypePolicy( self._coefficient, other._coefficient, operator.mul) # Compute the variables varDict = basicAlgorithms.combineDicts( [dict(self._vars),dict(other._vars)], operator.add) return Monomial(coefficient, varDict)