return quotient         elif self.is_Add:             cs, ps = self.primitive()            if cs is not S.One:                return Mul(cs, ps, evaluate=False).extract_multiplicatively(c)            # assert cs >= 1            if c.is_Number and c is not S.NegativeOne:                # assert c != 1 (handled at top)                if cs is not S.One:                    if c.is_negative:                        xc = -(cs.extract_multiplicatively(-c))                    else:                        xc = cs.extract_multiplicatively(c)                    if xc is not None:                        return xc*ps  # rely on 2-arg Mul to restore Add                return  # |c| != 1 can only be extracted from cs            if c == ps:                return cs            # check args of ps             newargs = []            for arg in self.args:            for arg in ps.args:                 newarg = arg.extract_multiplicatively(c)                if newarg is not None:                    newargs.append(newarg)                else:                    return None            return Add(*newargs)                if newarg is None:                    return  # all or nothing                newargs.append(newarg)            # args should be in same order so use unevaluated return            if cs is not S.One:                return Add._from_args([cs*t for t in newargs])            else:                return Add._from_args(newargs)         elif self.is_Mul:             args = list(self.args)             for i, arg in enumerate(args):


class Dummy(Symbol):    """Dummy symbols are each unique, identified by an internal count index:    """Dummy symbols are each unique, even if they have the same name:      >>> from sympy import Dummy    >>> bool(Dummy("x") == Dummy("x")) == True    >>> Dummy("x") == Dummy("x")     False     If a name is not supplied then a string value of the count index will be    If a name is not supplied then a string value of an internal count will be     used. This is useful when a temporary variable is needed and the name     of the variable used in the expression is not important.


"""     # In the rare event that a Dummy object needs to be recreated, both the    # `name` and `dummy_index` should be passed.  This is used by `srepr` for    # example:    # >>> d1 = Dummy()    # >>> d2 = eval(srepr(d1))    # >>> d2 == d1    # True    #    # If a new session is started between `srepr` and `eval`, there is a very    # small chance that `d2` will be equal to a previously-created Dummy.     _count = 0    _prng = random.Random()    _base_dummy_index = _prng.randint(10**6, 9*10**6)      __slots__ = ['dummy_index']      is_Dummy = True     def __new__(cls, name=None, **assumptions):    def __new__(cls, name=None, dummy_index=None, **assumptions):        if dummy_index is not None:            assert name is not None, "If you specify a dummy_index, you must also provide a name"         if name is None:             name = "Dummy_" + str(Dummy._count)         if dummy_index is None:            dummy_index = Dummy._base_dummy_index + Dummy._count            Dummy._count += 1         cls._sanitize(assumptions, cls)         obj = Symbol.__xnew__(cls, name, **assumptions)         Dummy._count += 1        obj.dummy_index = Dummy._count        obj.dummy_index = dummy_index         return obj      def __getstate__(self):diff --git a/sympy/printing/repr.py b/sympy/printing/repr.py-- a/sympy/printing/repr.py++ b/sympy/printing/repr.py


# remove it             if Func is Add:                 take = min(func_dicts[k][i] for i in com_dict)                com_func_take = Mul(take, from_dict(com_dict), evaluate=False)                _sum = from_dict(com_dict)                if take == 1:                    com_func_take = _sum                else:                    com_func_take = Mul(take, _sum, evaluate=False)             else:                 take = igcd(*[func_dicts[k][i] for i in com_dict])                com_func_take = Pow(from_dict(com_dict), take, evaluate=False)                base = from_dict(com_dict)                if take == 1:                    com_func_take = base                else:                    com_func_take = Pow(base, take, evaluate=False)             for di in com_dict:                 func_dicts[k][di] -= take*com_dict[di]             # compute the remaining expression


#     R = [(x0, d + f), (x1, b + d)]     #     C = [e + x0 + x1, g + x0 + x1, a + c + d + f + g]     # but the args of C[-1] should not be `(a + c, d + f + g)`    nested = [[i for i in f.args if isinstance(i, f.func)] for f in exprs]     for i in range(len(exprs)):         F = reduced_exprs[i].func         if not (F is Mul or F is Add):             continue        nested = [a for a in exprs[i].args if isinstance(a, F)]        args = []        for a in reduced_exprs[i].args:            if isinstance(a, F):                for ai in a.args:                    if isinstance(ai, F) and ai not in nested:                        args.extend(ai.args)                    else:                        args.append(ai)            else:                args.append(a)        reduced_exprs[i] = F(*args)        if any(isinstance(a, F) for a in reduced_exprs[i].args):            reduced_exprs[i] = F(*reduced_exprs[i].args)      return replacements, reduced_exprs


def _get_comment(self, text):         return "! {0}".format(text)<ins>#issue 12267    def _print_sign(self,func):        if func.args[0].is_integer:            return "merge(0, isign(1, {0}), {0} == 0)".format(self._print(func.args[0]))        elif func.args[0].is_complex:            return "merge(cmplx(0d0, 0d0), {0}/abs({0}), abs({0}) == 0d0)".format(self._print(func.args[0]))        else:            return "merge(0d0, dsign(1d0, {0}), {0} == 0d0)".format(self._print(func.args[0]))</ins>      def _declare_number_const(self, name, value):         return "parameter ({0} = {1})".format(name, value)


from functools import wraps from sympy.core import S, Symbol, Tuple, Integer, Basic, Exprfrom sympy.core import S, Symbol, Tuple, Integer, Basic, Expr, Eq from sympy.core.decorators import call_highest_priority from sympy.core.compatibility import range from sympy.core.sympify import SympifyError, sympify from sympy.functions import conjugate, adjointfrom sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices import ShapeError from sympy.simplify import simplify


if self.args[0] != v.args[0]:             return S.Zero <del>        from sympy import KroneckerDelta</del>         return KroneckerDelta(self.args[1], v.args[1])*KroneckerDelta(self.args[2], v.args[2])


return self      def _entry(self, i, j):        if i == j:        eq = Eq(i, j)        if eq is S.true:             return S.One        else:        elif eq is S.false:             return S.Zero        return KroneckerDelta(i, j)      def _eval_determinant(self):         return S.One


from __future__ import print_function, division  from sympy.matrices.expressions import MatrixExprfrom sympy.core import Sfrom sympy.core import S, Eqfrom sympy.functions.special.tensor_functions import KroneckerDelta class DiagonalMatrix(MatrixExpr):     arg = property(lambda self: self.args[0])     shape = property(lambda self: (self.arg.shape[0], self.arg.shape[0]))      def _entry(self, i, j):        return S.Zero if i != j else self.arg[i, 0]        eq = Eq(i, j)        if eq is S.false:            return S.Zero        elif eq is S.true:            return self.arg[i, i]        return self.arg[i, j]*KroneckerDelta(i, j)  class DiagonalOf(MatrixExpr):     arg = property(lambda self: self.args[0])


def _eval_is_upper_hessenberg(self):         return all(self[i, j].is_zero                    for i in range(2, self.rows)                   for j in range(i - 1))                   for j in range(min(self.cols, (i - 1))))      def _eval_values(self):         return [i for i in self if not i.is_zero]


"""         return all(self[i, j].is_zero                    for i in range(1, self.rows)                   for j in range(i))                   for j in range(min(i, self.cols)))      @property     def is_zero(self):


# counting starts from 1.          temp = flatten(args)        if has_dups(temp):            if is_cycle:                raise ValueError('there were repeated elements; to resolve '                'cycles use Cycle%s.' % ''.join([str(tuple(c)) for c in args]))            else:                raise ValueError('there were repeated elements.')        if has_dups(temp) and not is_cycle:            raise ValueError('there were repeated elements.')         temp = set(temp)          if not is_cycle and \


from sympy.core.compatibility import as_int, SYMPY_INTS, range from sympy.core.singleton import S from sympy.core.function import Function<ins>from sympy.core.expr import Expr</ins>  small_trailing = [i and max(int(not i % 2**j) and j for j in range(1, 8))     for i in range(256)]


for p, k in factors.items():                 t *= (p - 1) * p**(k - 1)             return t<ins>        elif not isinstance(n, Expr) or (n.is_integer is False) or (n.is_positive is False):            raise ValueError("n must be a positive integer")</ins>      def _eval_is_integer(self):         return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive])


from sympy.core.compatibility import reduce from sympy.combinatorics import Permutation <ins></ins> # TODO you are a bit excessive in the use of Dummies # TODO dummy point, literal field # TODO too often one needs to call doit or simplify on the output, check the


if covariant_order(scalar_field) or contravariant_order(scalar_field):             raise ValueError('Only scalar fields can be supplied as arguments to vector fields.') <ins>        if scalar_field is None:            return self</ins>         base_scalars = list(scalar_field.atoms(BaseScalarField))          # First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r)


"""Tensor product of forms.      The tensor product permits the creation of multilinear functionals (i.e.    higher order tensors) out of lower order forms (e.g. 1-forms). However, the    higher tensors thus created lack the interesting features provided by the    other type of product, the wedge product, namely they are not antisymmetric    and hence are not form fields.    higher order tensors) out of lower order fields (e.g. 1-forms and vector    fields). However, the higher tensors thus created lack the interesting    features provided by the other type of product, the wedge product, namely    they are not antisymmetric and hence are not form fields.      Examples     ========


0     >>> TensorProduct(R2.dx, R2.x*R2.dy)(R2.x*R2.e_x, R2.e_y)     x**2<ins>    >>> TensorProduct(R2.e_x, R2.e_y)(R2.x**2, R2.y**2)    4*x*y    >>> TensorProduct(R2.e_y, R2.dx)(R2.y)    dx</ins>      You can nest tensor products.


"""     def __new__(cls, *args):        if any(contravariant_order(a) for a in args):            raise ValueError('A vector field was supplied as an argument to TensorProduct.')        scalar = Mul(*[m for m in args if covariant_order(m) == 0])        forms = [m for m in args if covariant_order(m)]        if forms:            if len(forms) == 1:                return scalar*forms[0]            return scalar*super(TensorProduct, cls).__new__(cls, *forms)        scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0])        multifields = [m for m in args if covariant_order(m) + contravariant_order(m)]        if multifields:            if len(multifields) == 1:                return scalar*multifields[0]            return scalar*super(TensorProduct, cls).__new__(cls, *multifields)         else:             return scalar


super(TensorProduct, self).__init__()         self._args = args     def __call__(self, *v_fields):        """Apply on a list of vector_fields.    def __call__(self, *fields):        """Apply on a list of fields.         If the number of vector fields supplied is not equal to the order of        the form field the list of arguments is padded with ``None``'s.        If the number of input fields supplied is not equal to the order of        the tensor product field, the list of arguments is padded with ``None``'s.          The list of arguments is divided in sublists depending on the order of         the forms inside the tensor product. The sublists are provided as         arguments to these forms and the resulting expressions are given to the         constructor of ``TensorProduct``.         """        tot_order = covariant_order(self)        tot_args = len(v_fields)        tot_order = covariant_order(self) + contravariant_order(self)        tot_args = len(fields)         if tot_args != tot_order:            v_fields = list(v_fields) + [None]*(tot_order - tot_args)        orders = [covariant_order(f) for f in self._args]            fields = list(fields) + [None]*(tot_order - tot_args)        orders = [covariant_order(f) + contravariant_order(f) for f in self._args]         indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)]        v_fields = [v_fields[i:j] for i, j in zip([0] + indices, indices + [None])]        multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, v_fields)]        fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])]        multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)]         return TensorProduct(*multipliers)      def _latex(self, printer, *args):


-1     >>> WedgeProduct(R2.dx, R2.x*R2.dy)(R2.x*R2.e_x, R2.e_y)     x**2<ins>    >>> WedgeProduct(R2.e_x,R2.e_y)(R2.y,None)    -e_x</ins>      You can nest wedge products.


"""     # TODO the calculation of signatures is slow     # TODO you do not need all these permutations (neither the prefactor)    def __call__(self, *vector_fields):    def __call__(self, *fields):         """Apply on a list of vector_fields.          The expression is rewritten internally in terms of tensor products and evaluated."""        orders = (covariant_order(e) for e in self.args)        orders = (covariant_order(e) + contravariant_order(e) for e in self.args)         mul = 1/Mul(*(factorial(o) for o in orders))        perms = permutations(vector_fields)        perms = permutations(fields)         perms_par = (Permutation(            p).signature() for p in permutations(list(range(len(vector_fields)))))            p).signature() for p in permutations(list(range(len(fields)))))         tensor_prod = TensorProduct(*self.args)         return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])


return 0     elif isinstance(expr, BaseVectorField):         return 1<ins>    elif isinstance(expr, TensorProduct):        return sum(contravariant_order(a) for a in expr.args)</ins>     elif not _strict or expr.atoms(BaseScalarField):         return 0     else:  # If it does not contain anything related to the diffgeom module and it is _strict


========          >>> from sympy import Poly        >>> from sympy.abc import x, y        >>> from sympy.abc import x, y, z          >>> Poly(x**2 + 1).free_symbols         {x}


{x, y}         >>> Poly(x**2 + y, x).free_symbols         {x, y}        >>> Poly(x**2 + y, x, z).free_symbols        {x, y}          """        symbols = set([])        for gen in self.gens:            symbols |= gen.free_symbols        symbols = set()        gens = self.gens        for i in range(len(gens)):            for monom in self.monoms():                if monom[i]:                    symbols |= gens[i].free_symbols                    break          return symbols | self.free_symbols_in_domain


def ltrim(f, gen):         """        Remove dummy generators from the "left" of ``f``.        Remove dummy generators from ``f`` that are to the left of        specified ``gen`` in the generators as ordered. When ``gen``        is an integer, it refers to the generator located at that        position within the tuple of generators of ``f``.          Examples         ========


>>> Poly(y**2 + y*z**2, x, y, z).ltrim(y)         Poly(y**2 + y*z**2, y, z, domain='ZZ')        >>> Poly(z, x, y, z).ltrim(-1)        Poly(z, z, domain='ZZ')          """         rep = f.as_dict(native=True)         j = f._gen_to_level(gen)         terms = {}          for monom, coeff in rep.items():            monom = monom[j:]             if monom not in terms:                terms[monom] = coeff            else:            if any(i for i in monom[:j]):                # some generator is used in the portion to be trimmed                 raise PolynomialError("can't left trim %s" % f)             terms[monom[j:]] = coeff         gens = f.gens[j:]          return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens)


False          """        indices = set([])        indices = set()          for gen in gens:             try:diff --git a/sympy/solvers/polysys.py b/sympy/solvers/polysys.py-- a/sympy/solvers/polysys.py++ b/sympy/solvers/polysys.py


from sympy.polys import Poly, groebner, roots from sympy.polys.polytools import parallel_poly_from_expr from sympy.polys.polyerrors import (ComputationFailed,    PolificationFailed, CoercionFailed)    PolificationFailed, CoercionFailed, PolynomialError) from sympy.simplify import rcollect from sympy.utilities import default_sort_key, postfixes


if len(polys) == len(opt.gens) == 2:         f, g = polys         a, b = f.degree_list()        c, d = g.degree_list()        if a <= 2 and b <= 2 and c <= 2 and d <= 2:        if all(i <= 2 for i in f.degree_list() + g.degree_list()):             try:                 return solve_biquadratic(f, g, opt)             except SolveFailed:


if len(G) != 2:         raise SolveFailed     p, q = G     x, y = opt.gens    p, q = G    if not p.gcd(q).is_ground:        # not 0-dimensional        raise SolveFailed      p = Poly(p, x, expand=False)    q = q.ltrim(-1)     p_roots = [ rcollect(expr, y) for expr in roots(p).keys() ]    q = q.ltrim(-1)     q_roots = list(roots(q).keys())      solutions = []


def _is_univariate(f):         """Returns True if 'f' is univariate in its last variable. """         for monom in f.monoms():            if any(m > 0 for m in monom[:-1]):            if any(m for m in monom[:-1]):                 return False          return True


def _eval_subs(self, old, new):         from sympy import exp, log, Symbol         def _check(ct1, ct2, old):            """Return bool, pow where, if bool is True, then the exponent of            Pow `old` will combine with `pow` so the substitution is valid,            otherwise bool will be False,            """Return (bool, pow, remainder_pow) where, if bool is True, then the            exponent of Pow `old` will combine with `pow` so the substitution            is valid, otherwise bool will be False.            For noncommutative objects, `pow` will be an integer, and a factor            `Pow(old.base, remainder_pow)` needs to be included. If there is            no such factor, None is returned. For commutative objects,            remainder_pow is always None.              cti are the coefficient and terms of an exponent of self or old             In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)             will give y**2 since (b**x)**2 == b**(2*x); if that equality does             not hold then the substitution should not occur so `bool` will be             False.             """             coeff1, terms1 = ct1             coeff2, terms2 = ct2             if terms1 == terms2:                pow = coeff1/coeff2                try:                    pow = as_int(pow)                    combines = True                except ValueError:                    combines = Pow._eval_power(                        Pow(*old.as_base_exp(), evaluate=False),                        pow) is not None                return combines, pow            return False, None                if old.is_commutative:                    # Allow fractional powers for commutative objects                    pow = coeff1/coeff2                    try:                        pow = as_int(pow)                        combines = True                    except ValueError:                        combines = Pow._eval_power(                            Pow(*old.as_base_exp(), evaluate=False),                            pow) is not None                    return combines, pow, None                else:                    # With noncommutative symbols, substitute only integer powers                    if not isinstance(terms1, tuple):                        terms1 = (terms1,)                    if not all(term.is_integer for term in terms1):                        return False, None, None                    try:                        # Round pow toward zero                        pow, remainder = divmod(as_int(coeff1), as_int(coeff2))                        if pow < 0 and remainder != 0:                            pow += 1                            remainder -= as_int(coeff2)                        if remainder == 0:                            remainder_pow = None                        else:                            remainder_pow = Mul(remainder, *terms1)                        return True, pow, remainder_pow                    except ValueError:                        # Can't substitute                        pass            return False, None, None          if old == self.base:             return new**self.exp._subs(old, new)


if self.exp.is_Add is False:                 ct1 = self.exp.as_independent(Symbol, as_Add=False)                 ct2 = old.exp.as_independent(Symbol, as_Add=False)                ok, pow = _check(ct1, ct2, old)                ok, pow, remainder_pow = _check(ct1, ct2, old)                 if ok:                     # issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2                    return self.func(new, pow)                    result = self.func(new, pow)                    if remainder_pow is not None:                        result = Mul(result, Pow(old.base, remainder_pow))                    return result             else:  # b**(6*x+a).subs(b**(3*x), y) -> y**2 * b**a                 # exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))                 oarg = old.exp


for a in self.exp.args:                     newa = a._subs(old, new)                     ct1 = newa.as_coeff_mul()                    ok, pow = _check(ct1, ct2, old)                    ok, pow, remainder_pow = _check(ct1, ct2, old)                     if ok:                         new_l.append(new**pow)                        if remainder_pow is not None:                            o_al.append(remainder_pow)                         continue                    elif not old.is_commutative and not newa.is_integer:                        # If any term in the exponent is non-integer,                        # we do not do any substitutions in the noncommutative case                        return                     o_al.append(newa)                 if new_l:                     new_l.append(Pow(self.base, Add(*o_al), evaluate=False))


ct1 = old.args[0].as_independent(Symbol, as_Add=False)             ct2 = (self.exp*log(self.base)).as_independent(                 Symbol, as_Add=False)            ok, pow = _check(ct1, ct2, old)            ok, pow, remainder_pow = _check(ct1, ct2, old)             if ok:                return self.func(new, pow)  # (2**x).subs(exp(x*log(2)), z) -> z                result = self.func(new, pow)  # (2**x).subs(exp(x*log(2)), z) -> z                if remainder_pow is not None:                    result = Mul(result, Pow(old.base, remainder_pow))                return result      def as_base_exp(self):         """Return base and exp of self.


>>> C == A.row_insert(A.rows, Matrix(B))         True         """        if not self:            return type(self)(other)        # A null matrix can always be stacked (see  #10770)        if self.rows == 0 and self.cols != other.cols:            return self._new(0, other.cols, []).col_join(other)         A, B = self, other         if not A.cols == B.cols:             raise ShapeError()


>>> C == A.col_insert(A.cols, B)         True         """        if not self:            return type(self)(other)        # A null matrix can always be stacked (see  #10770)        if self.cols == 0 and self.rows != other.rows:            return self._new(other.rows, 0, []).row_join(other)         A, B = self, other         if not A.rows == B.rows:             raise ShapeError()


>>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5)     {1: x + y, 2: x**2 + x*y, 5: x**3*y**2 + y**5}     >>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5, True)    [x, y, x**2, y**5, x*y, x**3*y**2]    {x, x**2, y, y**5, x*y, x**3*y**2}     """     expr = S(expr)     poly_dict = {}


degrees = [(sum(degree_list(monom, *symbols)), monom)                        for monom in expr.args]             if separate:                return [monom[1] for monom in degrees]                return {monom[1] for monom in degrees}             else:                 for monom in degrees:                     degree, term = monom


poly_dict[0] = expr      if separate:        return list(poly_dict.values())        return set(poly_dict.values())     return poly_dict


args.append(a)                     else:                         args.append(newa)                if not _aresame(tuple(args), tail_args):                    tail = self.func(*args)                return self.func(x, tail)                return self.func(x, *args)          # this is the same as above, but there were no pure-number args to         # deal with


args.append(a)             else:                 args.append(newa)        if not _aresame(tuple(args), self.args):            return self.func(*args)        return self        return self.func(*args)      @classmethod     def make_args(cls, expr):


GeneratorsError, ) from sympy.utilities import group, sift, publicfrom sympy.utilities import group, sift, public, filldedent  import sympy.polys import mpmath


from sympy.polys import polyoptions as options from sympy.core.compatibility import iterable, rangefrom sympy.core.compatibility import iterable, range, ordered  @public class Poly(Expr):


p, _ = poly_from_expr(f.as_expr())         if gen not in p.gens:             return S.Zero<ins>    elif not f.is_Poly and len(f.free_symbols) > 1:        raise TypeError(filldedent('''         A symbolic generator of interest is required for a multivariate         expression like func = %s, e.g. degree(func, gen = %s) instead of         degree(func, gen = %s).        ''' % (f, next(ordered(f.free_symbols)), gen)))</ins>      return Integer(p.degree(gen))


if p.is_infinite or q.is_infinite or p is nan or q is nan:                 return nan             if (p == q or p == -q or                    p.is_Pow and p.exp.is_Integer and p.base == q or                    p.is_Pow and p.exp.is_integer and p.base == q and q.is_integer                    and p.exp.is_positive or                     p.is_integer and q == 1):                 return S.Zero


Substitutions containing any Symbol from ``ignore`` will be ignored.     """     from sympy.matrices.expressions import MatrixExpr, MatrixSymbol, MatMul, MatAdd<ins>    from sympy.matrices.expressions.matexpr import MatrixElement</ins>      if opt_subs is None:         opt_subs = dict()


if not isinstance(expr, (Basic, Unevaluated)):             return         if isinstance(expr, Basic) and (expr.is_Atom or expr.is_Order):        if isinstance(expr, Basic) and (expr.is_Atom or expr.is_Order or isinstance(expr, MatrixSymbol) or isinstance(expr, MatrixElement)):             if expr.is_Symbol:                 excluded_symbols.add(expr)             return


factors[i] = (dup_convert(f, K, K0), k)              coeff = K0.convert(coeff, K)            coeff = K0.quo(coeff, denom)             if K0_inexact is None:                coeff = coeff/denom            else:            if K0_inexact:                 for i, (f, k) in enumerate(factors):                    f = dup_quo_ground(f, denom, K0)                    max_norm = dup_max_norm(f, K0)                    f = dup_quo_ground(f, max_norm, K0)                     f = dup_convert(f, K0, K0_inexact)                     factors[i] = (f, k)                    coeff = K0.mul(coeff, K0.pow(max_norm, k))                  coeff = K0_inexact.convert(coeff, K0)                 K0 = K0_inexact


factors[i] = (dmp_convert(f, u, K, K0), k)              coeff = K0.convert(coeff, K)            coeff = K0.quo(coeff, denom)             if K0_inexact is None:                coeff = coeff/denom            else:            if K0_inexact:                 for i, (f, k) in enumerate(factors):                    f = dmp_quo_ground(f, denom, u, K0)                    max_norm = dmp_max_norm(f, u, K0)                    f = dmp_quo_ground(f, max_norm, u, K0)                     f = dmp_convert(f, u, K0, K0_inexact)                     factors[i] = (f, k)                    coeff = K0.mul(coeff, K0.pow(max_norm, k))                  coeff = K0_inexact.convert(coeff, K0)                 K0 = K0_inexact


from sympy.core.compatibility import (iterable,     ordered, range, as_int) from sympy.core.numbers import Float, I, pi, Rational, Integerfrom sympy.core.function import expand_log, count_ops, _mexpand, _coeff_isnegfrom sympy.core.function import expand_log, count_ops, _mexpand, _coeff_isneg, nfloat from sympy.core.rules import Transform from sympy.core.evaluate import global_evaluate from sympy.functions import (


return e  def simplify(expr, ratio=1.7, measure=count_ops, fu=False):def simplify(expr, ratio=1.7, measure=count_ops, rational=False):     """     Simplifies the given expression.


simplification strategies and then compares them using the measure     function, we get a completely different result that is still different     from the input expression by doing this.<ins>    If rational=True, Floats will be recast as Rationals before simplification.    If rational=None, Floats will be recast as Rationals but the result will    be recast as Floats. If rational=False(default) then nothing will be done    to the Floats.</ins>     """     expr = sympify(expr)


if len(expr.args) == 1 and len(expr.args[0].args) == 1 and \                isinstance(expr.args[0], expr.inverse(argindex=1)):                 return simplify(expr.args[0].args[0], ratio=ratio,                                measure=measure, fu=fu)        return expr.func(*[simplify(x, ratio=ratio, measure=measure, fu=fu)                                measure=measure, rational=rational)        return expr.func(*[simplify(x, ratio=ratio, measure=measure, rational=rational)                          for x in expr.args])      # TODO: Apply different strategies, considering expression pattern:


return choices[0]         return min(choices, key=measure) <ins>    # rationalize Floats    floats = False    if rational is not False and expr.has(Float):        floats = True        expr = nsimplify(expr, rational=True)</ins>     expr = bottom_up(expr, lambda w: w.normal())     expr = Mul(*powsimp(expr).as_content_primitive())     _e = cancel(expr)


if expr.has(BesselBase):         expr = besselsimp(expr)     if expr.has(TrigonometricFunction) and not fu or expr.has(            HyperbolicFunction):    if expr.has(TrigonometricFunction, HyperbolicFunction):         expr = trigsimp(expr, deep=True)      if expr.has(log):


expr = product_simplify(expr)      short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr)<ins>    short = shorter(short, cancel(short))</ins>     short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))     if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase):         short = exptrigsimp(short, simplify=False)


if measure(expr) > ratio*measure(original_expr):         expr = original_expr <ins>    # restore floats    if floats and rational is None:        expr = nfloat(expr, exponent=False)</ins>     return expr


short = shorter(short, cancel(short))     short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short)))     if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase):        short = exptrigsimp(short, simplify=False)        short = exptrigsimp(short)      # get rid of hollow 2-arg Mul factorization     hollow_mul = Transform(


def expander(fro):         def repl(nu, z):             if (nu % 1) == S(1)/2:                return exptrigsimp(trigsimp(unpolarify(                return simplify(trigsimp(unpolarify(                         fro(nu, z0).rewrite(besselj).rewrite(jn).expand(                             func=True)).subs(z0, z)))             elif nu.is_Integer and nu > 1:diff --git a/sympy/simplify/trigsimp.py b/sympy/simplify/trigsimp.py-- a/sympy/simplify/trigsimp.py++ b/sympy/simplify/trigsimp.py


return trigsimpfunc(expr)  def exptrigsimp(expr, simplify=True):def exptrigsimp(expr):     """     Simplifies exponential / trigonometric / hyperbolic functions.    When ``simplify`` is True (default) the expression obtained after the    simplification step will be then be passed through simplify to    precondition it so the final transformations will be applied.      Examples     ========


return min(*choices, key=count_ops)     newexpr = bottom_up(expr, exp_trig)     if simplify:        newexpr = newexpr.simplify()    # conversion from exp to hyperbolic    ex = newexpr.atoms(exp, S.Exp1)    ex = [ei for ei in ex if 1/ei not in ex]    ## sinh and cosh    for ei in ex:        e2 = ei**-2        if e2 in ex:            a = e2.args[0]/2 if not e2 is S.Exp1 else S.Half            newexpr = newexpr.subs((e2 + 1)*ei, 2*cosh(a))            newexpr = newexpr.subs((e2 - 1)*ei, 2*sinh(a))    ## exp ratios to tan and tanh    for ei in ex:        n, d = ei - 1, ei + 1        et = n/d        etinv = d/n  # not 1/et or else recursion errors arise        a = ei.args[0] if ei.func is exp else S.One        if a.is_Mul or a is S.ImaginaryUnit:            c = a.as_coefficient(I)            if c:                t = S.ImaginaryUnit*tan(c/2)                newexpr = newexpr.subs(etinv, 1/t)                newexpr = newexpr.subs(et, t)                continue        t = tanh(a/2)        newexpr = newexpr.subs(etinv, 1/t)        newexpr = newexpr.subs(et, t)    def f(rv):        if not rv.is_Mul:            return rv        rvd = rv.as_powers_dict()        newd = rvd.copy()        def signlog(expr, sign=1):            if expr is S.Exp1:                return sign, 1            elif isinstance(expr, exp):                return sign, expr.args[0]            elif sign == 1:                return signlog(-expr, sign=-1)            else:                return None, None        ee = rvd[S.Exp1]        for k in rvd:            if k.is_Add and len(k.args) == 2:                # k == c*(1 + sign*E**x)                c = k.args[0]                sign, x = signlog(k.args[1]/c)                if not x:                    continue                m = rvd[k]                newd[k] -= m                if ee == -x*m/2:                    # sinh and cosh                    newd[S.Exp1] -= ee                    ee = 0                    if sign == 1:                        newd[2*c*cosh(x/2)] += m                    else:                        newd[-2*c*sinh(x/2)] += m                elif newd[1 - sign*S.Exp1**x] == -m:                    # tanh                    del newd[1 - sign*S.Exp1**x]                    if sign == 1:                        newd[-c/tanh(x/2)] += m                    else:                        newd[-c*tanh(x/2)] += m                else:                    newd[1 + sign*S.Exp1**x] += m                    newd[c] += m        return Mul(*[k**newd[k] for k in newd])    newexpr = bottom_up(newexpr, f)      # sin/cos and sinh/cosh ratios to tan and tanh, respectively     if newexpr.has(HyperbolicFunction):


"""     from sympy import simplify, lcm_list    from sympy.functions.elementary.trigonometric import TrigonometricFunction    from sympy.functions.elementary.complexes import Abs    from sympy.functions.elementary.trigonometric import (        TrigonometricFunction, sin, cos, csc, sec)     from sympy.solvers.decompogen import decompogen    from sympy.core.relational import Relational    def _check(orig_f, period):        '''Return the checked period or raise an error.'''        new_f = orig_f.subs(symbol, symbol + period)        if new_f.equals(orig_f):            return period        else:            raise NotImplementedError(filldedent('''                The period of the given function cannot be verified.                When `%s` was replaced with `%s + %s` in `%s`, the result                was `%s` which was not recognized as being the same as                the original function.                So either the period was wrong or the two forms were                not recognized as being equal.                Set check=False to obtain the value.''' %                (symbol, symbol, period, orig_f, new_f)))      orig_f = f     f = simplify(orig_f)     period = None     if not f.has(symbol):    if symbol not in f.free_symbols:         return S.Zero     if isinstance(f, Relational):        f = f.lhs - f.rhs     if isinstance(f, TrigonometricFunction):         try:             period = f.period(symbol)         except NotImplementedError:             pass     if isinstance(f, Abs):        arg = f.args[0]        if isinstance(arg, (sec, csc, cos)):            # all but tan and cot might have a            # a period that is half as large            # so recast as sin            arg = sin(arg.args[0])        period = periodicity(arg, symbol)        if period is not None and isinstance(arg, sin):            # the argument of Abs was a trigonometric other than            # cot or tan; test to see if the half-period            # is valid. Abs(arg) has behaviour equivalent to            # orig_f, so use that for test:            orig_f = Abs(arg)            try:                return _check(orig_f, period/2)            except NotImplementedError as err:                if check:                    raise NotImplementedError(err)            # else let new orig_f and period be            # checked below     if f.is_Pow:         base, expo = f.args         base_has_sym = base.has(symbol)


if period is not None:         if check:            if orig_f.subs(symbol, symbol + period) == orig_f:                return period            else:                raise NotImplementedError(filldedent('''                    The period of the given function cannot be verified.                    Set check=False to obtain the value.'''))            return _check(orig_f, period)         return period      return Nonediff --git a/sympy/solvers/decompogen.py b/sympy/solvers/decompogen.py-- a/sympy/solvers/decompogen.py++ b/sympy/solvers/decompogen.py


from sympy.core import Function, Pow, sympifyfrom sympy.core import (Function, Pow, sympify, Expr)from sympy.core.relational import Relational from sympy.polys import Poly, decomposefrom sympy.utilities.misc import func_name   def decompogen(f, symbol):


"""     f = sympify(f)<ins>    if not isinstance(f, Expr) or isinstance(f, Relational):        raise TypeError('expecting Expr but got: `%s`' % func_name(f))    if symbol not in f.free_symbols:        return [f]</ins>     result = []      # ===== Simple Functions ===== #


>>> from sympy.abc import x      >>> AccumBounds(0, 1) + AccumBounds(1, 2)    <1, 3>    AccumBounds(1, 3)      >>> AccumBounds(0, 1) - AccumBounds(0, 2)    <-2, 1>    AccumBounds(-2, 1)      >>> AccumBounds(-2, 3)*AccumBounds(-1, 1)    <-3, 3>    AccumBounds(-3, 3)      >>> AccumBounds(1, 2)*AccumBounds(3, 5)    <3, 10>    AccumBounds(3, 10)      The exponentiation of AccumulationBounds is defined     as follows:


AccumulationBounds object is neglected.      >>> AccumBounds(-1, 4)**(S(1)/2)    <0, 2>    AccumBounds(0, 2)      >>> AccumBounds(1, 2)**2    <1, 4>    AccumBounds(1, 4)      >>> AccumBounds(-1, oo)**(-1)    <-oo, oo>    AccumBounds(-oo, oo)      Note: `<a, b>^2` is not same as `<a, b>*<a, b>`      >>> AccumBounds(-1, 1)**2    <0, 1>    AccumBounds(0, 1)      >>> AccumBounds(1, 3) < 4     True


is defined as `f(\langle a, b\rangle) = \{ f(x) \mid a \le x \le b \}`      >>> sin(AccumBounds(pi/6, pi/3))    <1/2, sqrt(3)/2>    AccumBounds(1/2, sqrt(3)/2)      >>> exp(AccumBounds(0, 1))    <1, E>    AccumBounds(1, E)      >>> log(AccumBounds(1, E))    <0, 1>    AccumBounds(0, 1)      Some symbol in an expression can be substituted for a AccumulationBounds     object. But it doesn't necessarily evaluate the AccumulationBounds for


the form it is used for substituion. For example:      >>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1))    <-1, 4>    AccumBounds(-1, 4)      >>> ((x + 1)**2).subs(x, AccumBounds(-1, 1))    <0, 4>    AccumBounds(0, 4)      References     ==========


>>> from sympy import AccumBounds, FiniteSet         >>> AccumBounds(1, 3).intersection(AccumBounds(2, 4))        <2, 3>        AccumBounds(2, 3)          >>> AccumBounds(1, 3).intersection(AccumBounds(4, 6))         EmptySet()diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py


return self._print_seq(i.args[:2], left, right)     def _print_AccumuBounds(self, i):    def _print_AccumulationBounds(self, i):         left = '<'         right = '>' diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


return fin.format(**{'a': a, 'b': b, 'm': m})      def _print_AccumulationBounds(self, i):        left = '<'        right = '>'        return "%s%s, %s%s" % \                (left, self._print(i.min), self._print(i.max), right)        return "AccumBounds(%s, %s)" % (self._print(i.min), self._print(i.max))      def _print_Inverse(self, I):         return "%s^-1" % self.parenthesize(I.arg, PRECEDENCE["Pow"])


from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.power import Powfrom sympy.core.relational import Equalityfrom sympy.core.relational import Equality, Relational from sympy.core.singleton import Singleton from sympy.core.symbol import Dummy from sympy.core.rules import Transform


from sympy.functions.elementary.integers import floor from sympy.logic.boolalg import And <ins>def _minmax_as_Piecewise(op, *args):    # helper for Min/Max rewrite as Piecewise    from sympy.functions.elementary.piecewise import Piecewise    ec = []    for i, a in enumerate(args):        c = []        for j in range(i + 1, len(args)):            c.append(Relational(a, args[j], op))        ec.append((a, And(*c)))    return Piecewise(*ec)</ins> class IdentityFunction(with_metaclass(Singleton, Lambda)):     """     The identity function


return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \                 for j in args]) <ins>    def _eval_rewrite_as_Piecewise(self, *args):        return _minmax_as_Piecewise('>=', *args)</ins>     def _eval_is_positive(self):         return fuzzy_or(a.is_positive for a in self.args)


return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \                 for j in args]) <ins>    def _eval_rewrite_as_Piecewise(self, *args):        return _minmax_as_Piecewise('<=', *args)</ins>     def _eval_is_positive(self):         return fuzzy_and(a.is_positive for a in self.args)


[(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()]     )) <del>    def _print_Integer(self, e):        return '%s(%d)' % (self._module_format('mpmath.mpf'), e)</del>     def _print_Float(self, e):         # XXX: This does not handle setting mpmath.mp.dps. It is assumed that         # the caller of the lambdified function will have set it to sufficient


x = fzero             nint += int(no*(mpf_cmp(x or fzero, fzero) == no))         nint = from_int(nint)        return nint, fastlog(nint) + 10        return nint, INF      re_, im_, re_acc, im_acc = None, None, None, None


if not result:                                 for root in _try_decompose(f):                                     _update_dict(result, root, 1)<ins>                        else:                            for r in _try_heuristics(f):                                _update_dict(result, r, 1)</ins>                     else:                         for root in _try_decompose(f):                             _update_dict(result, root, 1)


elif re.is_number:                 re = re._to_mpmath(prec, allow_ints=False)._mpf_                 reprec = prec            else:                raise NotImplementedError             if im == 0:                 im = None                 imprec = None             elif im.is_number:                 im = im._to_mpmath(prec, allow_ints=False)._mpf_                 imprec = prec            else:                raise NotImplementedError             r = re, im, reprec, imprec         except AttributeError:             raise NotImplementedError


@classmethod     def eval(cls, n, k_sym=None, symbols=None):<ins>        if n is S.Infinity:            if k_sym is None:                return S.Infinity            else:                raise ValueError("Bell polynomial is not defined")        if n.is_negative or n.is_integer is False:            raise ValueError("a non-negative integer expected")</ins>         if n.is_Integer and n.is_nonnegative:             if k_sym is None:                 return Integer(cls._bell(int(n)))


# it's a hexadecimal (coming from a pickled object)                 # assume that it is in standard form                 num = list(num)<ins>                # If we're loading an object pickled in Python 2 into                # Python 3, we may need to strip a tailing 'L' because                # of a shim for int on Python 3, see issue #13470.                if num[1].endswith('L'):                    num[1] = num[1][:-1]</ins>                 num[1] = long(num[1], 16)                 _mpf_ = tuple(num)             else:


x, m = _peeloff_ipi(arg)                 if m:                     cothm = coth(m)                    if cotm is S.ComplexInfinity:                    if cothm is S.ComplexInfinity:                         return coth(x)                     else: # cothm == 0                         return tanh(x)


# There is expression, which couldn't change by                 # as_numer_denom(). E.g. n**(2/3) + 1 --> (n**(2/3) + 1, 1).                 # We have to catch this case.                p = sum([self._eval_product(i, (k, a, n)) for i in p.as_coeff_Add()])                from sympy.concrete.summations import Sum                p = exp(Sum(log(p), (k, a, n)))             else:                 p = self._eval_product(p, (k, a, n))             return p / q


out[j, i] = out[i, j]     return out <ins></ins> def jordan_cell(eigenval, n):     """     Create a Jordan block:


>>> A == randMatrix(3, seed=1)     True     >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP    [0, 68, 43]    [0, 68,  0]    [0, 91, 34]    [77, 70,  0],    [70,  0,  0],    [ 0,  0, 88]     """     if c is None:         c = r     # Note that ``Random()`` is equivalent to ``Random(None)``     prng = prng or random.Random(seed)    if symmetric and r != c:        raise ValueError(            'For symmetric matrices, r must equal c, but %i != %i' % (r, c))     if not symmetric:         m = Matrix._new(r, c, lambda i, j: prng.randint(min, max))    else:        m = zeros(r)        for i in range(r):            for j in range(i, r):                m[i, j] = prng.randint(min, max)        for i in range(r):            for j in range(i):                m[i, j] = m[j, i]    if percent == 100:        return m    else:        z = int(r*c*percent // 100)        if percent == 100:            return m        z = int(r*c*(100 - percent) // 100)         m._mat[:z] = [S.Zero]*z         prng.shuffle(m._mat)        return m    # Symmetric case    if r != c:        raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c))    m = zeros(r)    ij = [(i, j) for i in range(r) for j in range(i, r)]    if percent != 100:        ij = prng.sample(ij, int(len(ij)*percent // 100))    for i, j in ij:        value = prng.randint(min, max)        m[i, j] = m[j, i] = value     return m


elif (qinner*(q + qinner)).is_nonpositive:                 # |qinner| < |q| and have different sign                 return p<ins>        elif isinstance(p, Add):            # separating into modulus and non modulus            both_l = non_mod_l, mod_l = [], []            for arg in p.args:                both_l[isinstance(arg, cls)].append(arg)            # if q same for all            if mod_l and all(inner.args[1] == q for inner in mod_l):                net = Add(*non_mod_l) + Add(*[i.args[0] for i in mod_l])                return cls(net, q)        elif isinstance(p, Mul):            # separating into modulus and non modulus            both_l = non_mod_l, mod_l = [], []            for arg in p.args:                both_l[isinstance(arg, cls)].append(arg)            if mod_l and all(inner.args[1] == q for inner in mod_l):                # finding distributive term                non_mod_l = [cls(x, q) for x in non_mod_l]                mod = []                non_mod = []                for j in non_mod_l:                    if isinstance(j, cls):                        mod.append(j.args[0])                    else:                        non_mod.append(j)                prod_mod = Mul(*mod)                prod_non_mod = Mul(*non_mod)                prod_mod1 = Mul(*[i.args[0] for i in mod_l])                net = prod_mod1*prod_mod                return prod_non_mod*cls(net, q)</ins>         # XXX other possibilities?          # extract gcd; any further simplification should be done by the user


"""         other = _sympify(other)        if not (other.is_Symbol or other.is_number):            raise TypeError("Input of type real symbol or Number expected")          if other is S.Infinity or other is S.NegativeInfinity:             if self.min is S.NegativeInfinity or self.max is S.Infinity:                 return True             return False         return And(self.min <= other and self.max >= other)        rv = And(self.min <= other, self.max >= other)        if rv not in (True, False):            raise TypeError("input failed to evaluate")        return rv      def intersection(self, other):         """diff --git a/sympy/core/basic.py b/sympy/core/basic.py-- a/sympy/core/basic.py++ b/sympy/core/basic.py


is_real = self.is_real         if is_real is False:             return False        is_number = self.is_number        if is_number is False:        if not self.is_number:             return False        # don't re-eval numbers that are already evaluated since        # this will create spurious precision         n, i = [p.evalf(2) if not p.is_Number else p             for p in self.as_real_imag()]        if not i.is_Number or not n.is_Number:        if not (i.is_Number and n.is_Number):             return False         if i:             # if _prec = 1 we can't decide and if not,diff --git a/sympy/core/expr.py b/sympy/core/expr.py-- a/sympy/core/expr.py++ b/sympy/core/expr.py


@property     def is_number(self):        """Returns True if ``self`` has no free symbols.        It will be faster than ``if not self.free_symbols``, however, since        ``is_number`` will fail as soon as it hits a free symbol.        """Returns True if ``self`` has no free symbols and no        undefined functions (AppliedUndef, to be precise). It will be        faster than ``if not self.free_symbols``, however, since        ``is_number`` will fail as soon as it hits a free symbol        or undefined function.          Examples         ========         >>> from sympy import log, Integral        >>> from sympy import log, Integral, cos, sin, pi        >>> from sympy.core.function import Function         >>> from sympy.abc import x        >>> f = Function('f')          >>> x.is_number         False        >>> f(1).is_number        False         >>> (2*x).is_number         False        >>> (2 + log(2)).is_number        True         >>> (2 + Integral(2, x)).is_number         False         >>> (2 + Integral(2, (x, 1, 2))).is_number         True         Not all numbers are Numbers in the SymPy sense:        >>> pi.is_number, pi.is_Number        (True, False)        If something is a number it should evaluate to a number with        real and imaginary parts that are Numbers; the result may not        be comparable, however, since the real and/or imaginary part        of the result may not have precision.        >>> cos(1).is_number and cos(1).is_comparable        True        >>> z = cos(1)**2 + sin(1)**2 - 1        >>> z.is_number        True        >>> z.is_comparable        False        See Also        ========        sympy.core.basic.is_comparable         """         return all(obj.is_number for obj in self.args)


simplify = flags.get('simplify', True)         # Except for expressions that contain units, only one of these should        # be necessary since if something is        # known to be a number it should also know that there are no        # free symbols. But is_number quits as soon as it hits a non-number        # whereas free_symbols goes until all free symbols have been collected,        # thus is_number should be faster. But a double check on free symbols        # is made just in case there is a discrepancy between the two.        free = self.free_symbols        if self.is_number or not free:            # if the following assertion fails then that object's free_symbols            # method needs attention: if an expression is a number it cannot            # have free symbols            assert not free        if self.is_number:             return True        free = self.free_symbols        if not free:            return True  # assume f(1) is some constant          # if we are only interested in some symbols and they are not in the         # free symbols then this expression is constant wrt those symbols


def _n2(a, b):    """Return (a - b).evalf(2) if it, a and b are comparable, else None.    """Return (a - b).evalf(2) if a and b are comparable, else None.     This should only be used when a and b are already sympified.     """    if not all(i.is_number for i in (a, b)):        return    # /!\ if is very important (see issue 8245) not to    # /!\ it is very important (see issue 8245) not to     # use a re-evaluated number in the calculation of dif     if a.is_comparable and b.is_comparable:         dif = (a - b).evalf(2)diff --git a/sympy/core/function.py b/sympy/core/function.py-- a/sympy/core/function.py++ b/sympy/core/function.py


function.     """     is_number = False     def __new__(cls, *args, **options):         args = list(map(sympify, args))         obj = super(AppliedUndef, cls).__new__(cls, *args, **options)diff --git a/sympy/functions/elementary/miscellaneous.py b/sympy/functions/elementary/miscellaneous.py-- a/sympy/functions/elementary/miscellaneous.py++ b/sympy/functions/elementary/miscellaneous.py


from sympy.core.containers import Tuple from sympy.core.operations import LatticeOp, ShortCircuit from sympy.core.function import (Application, Lambda,    ArgumentIndexError, AppliedUndef)    ArgumentIndexError) from sympy.core.expr import Expr from sympy.core.mul import Mul from sympy.core.numbers import Rational


# pre-filter, checking comparability of arguments             if not isinstance(arg, Expr) or arg.is_real is False or (                     arg.is_number and<del>                    not arg.has(AppliedUndef) and</del>                     not arg.is_comparable):                 raise ValueError("The argument '%s' is not comparable." % arg)


code0 = self._print(temp)                 lines.append(code0)             return "\n".join(lines)        elif self._settings["contract"] and (lhs.has(IndexedBase) or        elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or                 rhs.has(IndexedBase)):             # Here we check if there is looping to be done, and if so             # print the required loops.diff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py-- a/sympy/printing/pycode.py++ b/sympy/printing/pycode.py


def _format_code(self, lines):         return lines <ins>    def _get_statement(self, codestring):        return "%s" % codestring</ins>     def _get_comment(self, text):         return "  # {0}".format(text)


return self[i, j]             elif pos <= j < pos + other.cols:                 return other[i, j - pos]            return self[i, j - pos - other.cols]            return self[i, j - other.cols]          return self._new(self.rows, self.cols + other.cols,                          lambda i, j: entry(i, j))


else:             return 'O(%s)' % self.stringify(expr.args, ', ', 0)     def _print_Ordinal(self, expr):        return expr.__str__()     def _print_Cycle(self, expr):         return expr.__str__() diff --git a/sympy/sets/__init__.py b/sympy/sets/__init__.py-- a/sympy/sets/__init__.py++ b/sympy/sets/__init__.py


from .fancysets import ImageSet, Range, ComplexRegion from .contains import Contains from .conditionset import ConditionSetfrom .ordinals import Ordinal, OmegaPower, ord0 from ..core.singleton import S Reals = S.Reals del Sdiff --git a/sympy/sets/ordinals.py b/sympy/sets/ordinals.pynew file mode 100644-- /dev/null++ b/sympy/sets/ordinals.py


<ins>from sympy.core import Basic, Integerfrom sympy.core.compatibility import with_metaclassfrom sympy.core.singleton import Singleton, Simport operatorclass OmegaPower(Basic):    """    Represents ordinal exponential and multiplication terms one of the    building blocks of the Ordinal class.    In OmegaPower(a, b) a represents exponent and b represents multiplicity.    """    def __new__(cls, a, b):        if isinstance(b, int):            b = Integer(b)        if not isinstance(b, Integer) or b <= 0:            raise TypeError("multiplicity must be a positive integer")        if not isinstance(a, Ordinal):            a = Ordinal.convert(a)        return Basic.__new__(cls, a, b)    @property    def exp(self):        return self.args[0]    @property    def mult(self):        return self.args[1]    def _compare_term(self, other, op):        if self.exp == other.exp:            return op(self.mult, other.mult)        else:            return op(self.exp, other.exp)    def __eq__(self, other):        if not isinstance(other, OmegaPower):            try:                other = OmegaPower(0, other)            except TypeError:                return NotImplemented        return self.args == other.args    __hash__ = Basic.__hash__    def __lt__(self, other):        if not isinstance(other, OmegaPower):            try:                other = OmegaPower(0, other)            except TypeError:                return NotImplemented        return self._compare_term(other, operator.lt)class Ordinal(Basic):    """    Represents ordinals in Cantor normal form.    Internally, this class is just a list of instances of OmegaPower    Examples    ========    >>> from sympy.sets import Ordinal, ord0, OmegaPower    >>> from sympy.sets.ordinals import omega    >>> w = omega    >>> w.is_limit_ordinal    True    >>> Ordinal(OmegaPower(w + 1 ,1), OmegaPower(3, 2))    w**(w + 1) + w**3*2    >>> 3 + w    w    >>> (w + 1) * w    w**2    References    ==========    .. [1] https://en.wikipedia.org/wiki/Ordinal_arithmetic    """    def __new__(cls, *terms):        obj = super(Ordinal, cls).__new__(cls, *terms)        powers = [i.exp for i in obj.args]        if not all(powers[i] >= powers[i+1] for i in range(len(powers) - 1)):            raise ValueError("powers must be in decreasing order")        return obj    @property    def leading_term(self):        if self == ord0:            raise ValueError("ordinal zero has no leading term")        return self.args[0]    @property    def trailing_term(self):        if self == ord0:            raise ValueError("ordinal zero has no trailing term")        return self.args[-1]    @property    def is_successor_ordinal(self):        try:            return self.trailing_term.exp == ord0        except ValueError:            return False    @property    def is_limit_ordinal(self):        try:            return not self.trailing_term.exp == ord0        except ValueError:            return False    @property    def degree(self):        return self.leading_term.exp    @classmethod    def convert(cls, integer_value):        if integer_value == 0:            return ord0        return Ordinal(OmegaPower(0, integer_value))    def __eq__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        return self.args == other.args    def __hash__(self):        return hash(self.args)    def __lt__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        for term_self, term_other in zip(self.args, other.args):            if term_self != term_other:                return term_self < term_other        return len(self.args) < len(other.args)    def __le__(self, other):        return (self == other or self < other)    def __gt__(self, other):        return not self <= other    def __ge__(self, other):        return not self < other    def __str__(self):        net_str = ""        plus_count = 0        if self == ord0:            return 'ord0'        for i in self.args:            if plus_count:                net_str += " + "            if i.exp == ord0:                net_str += str(i.mult)            elif i.exp == 1:                net_str += 'w'            elif len(i.exp.args) > 1 or i.exp.is_limit_ordinal:                net_str += 'w**(%s)'%i.exp            else:                net_str += 'w**%s'%i.exp            if not i.mult == 1 and not i.exp == ord0:                net_str += '*%s'%i.mult            plus_count += 1        return(net_str)    __repr__ = __str__    def __add__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        if other == ord0:            return self        a_terms = list(self.args)        b_terms = list(other.args)        r = len(a_terms) - 1        b_exp = other.degree        while r >= 0 and a_terms[r].exp < b_exp:            r -= 1        if r < 0:            terms = b_terms        elif a_terms[r].exp == b_exp:            sum_term = OmegaPower(b_exp, a_terms[r].mult + other.leading_term.mult)            terms = a_terms[:r] + [sum_term] + b_terms[1:]        else:            terms = a_terms[:r+1] + b_terms        return Ordinal(*terms)    def __radd__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        return other + self    def __mul__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        if ord0 in (self, other):            return ord0        a_exp = self.degree        a_mult = self.leading_term.mult        sum = []        if other.is_limit_ordinal:            for arg in other.args:                sum.append(OmegaPower(a_exp + arg.exp, arg.mult))        else:            for arg in other.args[:-1]:                sum.append(OmegaPower(a_exp + arg.exp, arg.mult))            b_mult = other.trailing_term.mult            sum.append(OmegaPower(a_exp, a_mult*b_mult))            sum += list(self.args[1:])        return Ordinal(*sum)    def __rmul__(self, other):        if not isinstance(other, Ordinal):            try:                other = Ordinal.convert(other)            except TypeError:                return NotImplemented        return other * self    def __pow__(self, other):        if not self == omega:            return NotImplemented        return Ordinal(OmegaPower(other, 1))class OrdinalZero(with_metaclass(Singleton, Ordinal)):    """The ordinal zero.    OrdinalZero is a singleton, and can be accessed by ``S.OrdinalZero``    or can be imported as ``ord0``.    Examples    ========    >>> from sympy import ord0, S    >>> ord0 is S.OrdinalZero    True    """    passclass OrdinalOmega(with_metaclass(Singleton, Ordinal)):    """The ordinal omega which forms the base of all ordinals in cantor normal form.    OrdinalOmega is a singleton, and can be accessed by ``S.OrdinalOmega``    or can be imported as ``omega``.    Examples    ========    >>> from sympy.sets.ordinals import omega    >>> from sympy import S    >>> omega is S.OrdinalOmega    True    """    def __new__(cls):        return Ordinal.__new__(cls, OmegaPower(1, 1))ord0 = S.OrdinalZeroomega = S.OrdinalOmega</ins>


def zero_mul_simp(l, index):     """Used to combine two reduced words."""    while index >=0 and index < len(l) - 1 and l[index][0] is l[index + 1][0]:    while index >=0 and index < len(l) - 1 and l[index][0] == l[index + 1][0]:         exp = l[index][1] + l[index + 1][1]         base = l[index][0]         l[index] = (base, exp)diff --git a/sympy/combinatorics/rewritingsystem.py b/sympy/combinatorics/rewritingsystem.py-- a/sympy/combinatorics/rewritingsystem.py++ b/sympy/combinatorics/rewritingsystem.py


s1 = s1.subword(0, len(s1)-1)             s2 = s2*g**-1             if len(s1) - len(s2) < 0:<del>                #print("this", len(s1)-len(s2))</del>                 if s2 not in self.rules:                     if not check:                         self._add_rule(s2, s1)


is_commutative = True     is_Poly = True<ins>    _op_priority = 10.001</ins>      def __new__(cls, rep, *gens, **args):         """Create a new polynomial instance out of something useful. """


bernoulli(2*k)*x**(2*k - 1)/factorial(2*k))  class sinc(TrigonometricFunction):class sinc(Function):     r"""Represents unnormalized sinc function      Examples


from sympy.core.compatibility import (is_sequence, default_sort_key, range,     NotIterable) <ins>from sympy.utilities.exceptions import SymPyDeprecationWarning</ins>  from types import FunctionType


# https://github.com/sympy/sympy/pull/12854 class MatrixDeprecated(MatrixCommon):     """A class to house deprecated matrix methods."""<ins>    def _legacy_array_dot(self, b):        """Compatibility function for deprecated behavior of ``matrix.dot(vector)``        """        from .dense import Matrix        if not isinstance(b, MatrixBase):            if is_sequence(b):                if len(b) != self.cols and len(b) != self.rows:                    raise ShapeError(                        "Dimensions incorrect for dot product: %s, %s" % (                            self.shape, len(b)))                return self.dot(Matrix(b))            else:                raise TypeError(                    "`b` must be an ordered iterable or Matrix, not %s." %                    type(b))        mat = self        if mat.cols == b.rows:            if b.cols != 1:                mat = mat.T                b = b.T            prod = flatten((mat * b).tolist())            return prod        if mat.cols == b.cols:            return mat.dot(b.T)        elif mat.rows == b.rows:            return mat.T.dot(b)        else:            raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (                self.shape, b.shape))</ins>      def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify):         return self.charpoly(x=x)


return self._diagonal_solve(rhs)      def dot(self, b):        """Return the dot product of Matrix self and b relaxing the condition        of compatible dimensions: if either the number of rows or columns are        the same as the length of b then the dot product is returned. If self        is a row or column vector, a scalar is returned. Otherwise, a list        of results is returned (and in that case the number of columns in self        must match the length of b).        """Return the dot product of two vectors of equal length. ``self`` must        be a ``Matrix`` of size 1 x n or n x 1, and ``b`` must be either a        matrix of size 1 x n, n x 1, or a list/tuple of length n. A scalar is returned.          Examples         ========          >>> from sympy import Matrix         >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])        >>> v = [1, 1, 1]        >>> v = Matrix([1, 1, 1])         >>> M.row(0).dot(v)         6         >>> M.col(0).dot(v)         12        >>> M.dot(v)        [6, 15, 24]        >>> v = [3, 2, 1]        >>> M.row(0).dot(v)        10          See Also         ========


type(b))          mat = self        if mat.cols == b.rows:            if b.cols != 1:                mat = mat.T                b = b.T            prod = flatten((mat * b).tolist())            if len(prod) == 1:                return prod[0]            return prod        if mat.cols == b.cols:            return mat.dot(b.T)        elif mat.rows == b.rows:            return mat.T.dot(b)        else:            raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (                self.shape, b.shape))        if (1 not in mat.shape) or (1 not in b.shape) :            SymPyDeprecationWarning(                feature="Dot product of non row/column vectors",                issue=13815,                deprecated_since_version="1.2").warn()            return mat._legacy_array_dot(b)        if len(mat) != len(b):            raise ShapeError("Dimensions incorrect for dot product: %s, %s" % (self.shape, b.shape))        n = len(mat)        if mat.shape != (1, n):            mat = mat.reshape(1, n)        if b.shape != (n, 1):            b = b.reshape(n, 1)        # Now ``mat`` is a row vector and ``b`` is a column vector.        return (mat * b)[0]      def dual(self):         """Returns the dual of a matrix, which is:


@call_highest_priority('__rmatmul__')     def __matmul__(self, other):<ins>        other = _matrixify(other)        if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):            return NotImplemented</ins>         return self.__mul__(other)      @call_highest_priority('__rmul__')


@call_highest_priority('__matmul__')     def __rmatmul__(self, other):<ins>        other = _matrixify(other)        if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):            return NotImplemented</ins>         return self.__rmul__(other)      @call_highest_priority('__mul__')


"dot": r" \cdot ",             "times": r" \times "         }        self._settings['mul_symbol_latex'] = \            mul_symbol_table[self._settings['mul_symbol']]        self._settings['mul_symbol_latex_numbers'] = \            mul_symbol_table[self._settings['mul_symbol'] or 'dot']        try:            self._settings['mul_symbol_latex'] = \                mul_symbol_table[self._settings['mul_symbol']]        except KeyError:            self._settings['mul_symbol_latex'] = \                self._settings['mul_symbol']        try:            self._settings['mul_symbol_latex_numbers'] = \                mul_symbol_table[self._settings['mul_symbol'] or 'dot']        except KeyError:            if (self._settings['mul_symbol'].strip() in                    ['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']):                self._settings['mul_symbol_latex_numbers'] = \                    mul_symbol_table['dot']            else:                self._settings['mul_symbol_latex_numbers'] = \                    self._settings['mul_symbol']          self._delim_dict = {'(': ')', '[': ']'}


def _print_Mul(self, expr):         from sympy.core.power import Pow<ins>        from sympy.physics.units import Quantity</ins>         include_parens = False         if _coeff_isneg(expr):             expr = -expr


if self.order not in ('old', 'none'):                     args = expr.as_ordered_factors()                 else:                    args = expr.args                    args = list(expr.args)                # If quantities are present append them at the back                args = sorted(args, key=lambda x: isinstance(x, Quantity) or                             (isinstance(x, Pow) and isinstance(x.base, Quantity)))                  for i, term in enumerate(args):                     term_tex = self._print(term)


self._print(exp))         return r'\Omega\left(%s\right)' % self._print(expr.args[0])     def _print_Quantity(self, expr):        if expr.name.name == 'degree':            return r"^\circ"        return r"%s" % expr  def translate(s):     r'''diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py


return prettyForm.__add__(*pforms)      def _print_Mul(self, product):        from sympy.physics.units import Quantity         a = []  # items in the numerator         b = []  # items that are in the denominator (if any)          if self.order not in ('old', 'none'):             args = product.as_ordered_factors()         else:            args = product.args            args = list(product.args)        # If quantities are present append them at the back        args = sorted(args, key=lambda x: isinstance(x, Quantity) or                     (isinstance(x, Pow) and isinstance(x.base, Quantity)))          # Gather terms for numerator/denominator         for item in args:


pform = prettyForm(*pform.left('Omega'))         return pform     def _print_Quantity(self, e):        if e.name.name == 'degree':            pform = self._print(u"\N{DEGREE SIGN}")            return pform        else:            return self.emptyPrinter(e)  def pretty(expr, **settings):     """Returns a string containing the prettified form of expr.diff --git a/sympy/printing/pretty/stringpict.py b/sympy/printing/pretty/stringpict.py-- a/sympy/printing/pretty/stringpict.py++ b/sympy/printing/pretty/stringpict.py


"""Make a pretty multiplication.         Parentheses are needed around +, - and neg.         """        quantity = {            'degree': u"\N{DEGREE SIGN}"        }         if len(others) == 0:             return self # We aren't actually multiplying... So nothing to do here.         args = self         if args.binding > prettyForm.MUL:             arg = stringPict(*args.parens())         result = [args]         for arg in others:            result.append(xsym('*'))            if arg.picture[0] not in quantity.values():                result.append(xsym('*'))             #add parentheses for weak binders             if arg.binding > prettyForm.MUL:                 arg = stringPict(*arg.parens())


from sympy.core.expr import Expr from sympy.core.function import diff from sympy.core.mul import Mulfrom sympy.core.numbers import oofrom sympy.core.numbers import oo, pi from sympy.core.relational import Eq, Ne from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild)


from sympy.matrices import MatrixBase from sympy.utilities.misc import filldedent from sympy.polys import Poly, PolynomialErrorfrom sympy.functions import Piecewise, sqrt, sign, piecewise_foldfrom sympy.functions.elementary.complexes import Abs, signfrom sympy.functions import Piecewise, sqrt, sign, piecewise_fold, tan, cot, atan from sympy.functions.elementary.exponential import logfrom sympy.functions.elementary.integers import floorfrom sympy.functions.elementary.complexes import Abs, sign from sympy.functions.elementary.miscellaneous import Min, Max from sympy.series import limit from sympy.series.order import Order


function = ret                             continue <ins>            if not isinstance(antideriv, Integral) and antideriv is not None:                sym = xab[0]                for atan_term in antideriv.atoms(atan):                    atan_arg = atan_term.args[0]                    # Checking `atan_arg` to be linear combination of `tan` or `cot`                    for tan_part in atan_arg.atoms(tan):                        x1 = Dummy('x1')                        tan_exp1 = atan_arg.subs(tan_part, x1)                        # The coefficient of `tan` should be constant                        coeff = tan_exp1.diff(x1)                        if x1 not in coeff.free_symbols:                            a = tan_part.args[0]                            antideriv = antideriv.subs(atan_term, Add(atan_term,                                sign(coeff)*pi*floor((a-pi/2)/pi)))                    for cot_part in atan_arg.atoms(cot):                        x1 = Dummy('x1')                        cot_exp1 = atan_arg.subs(cot_part, x1)                        # The coefficient of `cot` should be constant                        coeff = cot_exp1.diff(x1)                        if x1 not in coeff.free_symbols:                            a = cot_part.args[0]                            antideriv = antideriv.subs(atan_term, Add(atan_term,                                sign(coeff)*pi*floor((a)/pi)))</ins>             if antideriv is None:                 undone_limits.append(xab)                 function = self.func(*([function] + [xab])).factor()


known_functions = {     #"Abs": [(lambda x: not x.is_integer, "fabs")],     "Abs": "abs",<del>    "gamma": "gamma",</del>     "sin": "sin",     "cos": "cos",     "tan": "tan",


"floor": "floor",     "ceiling": "ceiling",     "sign": "sign",<ins>    "Max": "max",    "Min": "min",    "factorial": "factorial",    "gamma": "gamma",    "digamma": "digamma",    "trigamma": "trigamma",    "beta": "beta",</ins> }  # These are the core reserved words in the R language. Taken from:


""" Riemann zeta and related function. """ from __future__ import print_function, division from sympy.core import Function, S, sympify, pifrom sympy.core import Function, S, sympify, pi, I from sympy.core.function import ArgumentIndexError from sympy.core.compatibility import range from sympy.functions.combinatorial.numbers import bernoulli, factorial, harmonic from sympy.functions.elementary.exponential import logfrom sympy.functions.elementary.miscellaneous import sqrt  ############################################################################### ###################### LERCH TRANSCENDENT #####################################


>>> from sympy import expand_func     >>> from sympy.abc import z     >>> expand_func(polylog(1, z))    -log(z*exp_polar(-I*pi) + 1)    -log(-z + 1)     >>> expand_func(polylog(0, z))     z/(-z + 1)


elif z == -1:             return -dirichlet_eta(s)         elif z == 0:            return 0            return S.Zero        elif s == 2:            if z == S.Half:                return pi**2/12 - log(2)**2/2            elif z == 2:                return pi**2/4 - I*pi*log(2)            elif z == -(sqrt(5) - 1)/2:                return -pi**2/15 + log((sqrt(5)-1)/2)**2/2            elif z == -(sqrt(5) + 1)/2:                return -pi**2/10 - log((sqrt(5)+1)/2)**2            elif z == (3 - sqrt(5))/2:                return pi**2/15 - log((sqrt(5)-1)/2)**2            elif z == (sqrt(5) - 1)/2:                return pi**2/10 - log((sqrt(5)-1)/2)**2        # For s = 0 or -1 use explicit formulas to evaluate, but        # automatically expanding polylog(1, z) to -log(1-z) seems undesirable        # for summation methods based on hypergeometric functions        elif s == 0:            return z/(1 - z)        elif s == -1:            return z/(1 - z)**2      def fdiff(self, argindex=1):         s, z = self.args


from sympy import log, expand_mul, Dummy, exp_polar, I         s, z = self.args         if s == 1:            return -log(1 + exp_polar(-I*pi)*z)            return -log(1 - z)         if s.is_Integer and s <= 0:             u = Dummy('u')             start = u/(1 - u)


d = Wild('d', exclude=[df, f(x).diff(x, 2)])     e = Wild('e', exclude=[df])     k = Wild('k', exclude=[df])    n = Wild('n', exclude=[f(x)])    n = Wild('n', exclude=[x, f(x), df])     c1 = Wild('c1', exclude=[x])     a2 = Wild('a2', exclude=[x, f(x), df])     b2 = Wild('b2', exclude=[x, f(x), df])


from sympy.core.add import Add from sympy.core.basic import Basic, Atom from sympy.core.expr import Expr<ins>from sympy.core.function import expand_mul</ins> from sympy.core.power import Pow from sympy.core.symbol import (Symbol, Dummy, symbols,     _uniquely_named_symbol)


from sympy.utilities.iterables import flatten, numbered_symbols from sympy.core.decorators import call_highest_priorityfrom sympy.core.compatibility import is_sequence, default_sort_key, range, \    NotIterablefrom sympy.core.compatibility import (is_sequence, default_sort_key, range,    NotIterable)   from types import FunctionType


return None  <ins>def _is_zero_after_expand_mul(x):    """Tests by expand_mul only, suitable for polynomials and rational    functions."""    return expand_mul(x) == 0</ins> class DeferredVector(Symbol, NotIterable):     """A vector whose components are deferred (e.g. for use with lambdify)


http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.         """ <del>        # XXX included as a workaround for issue #12362.  Should use `_find_reasonable_pivot` instead        def _find_pivot(l):            for pos,val in enumerate(l):                if val:                    return (pos, val, None, None)            return (None, None, None, None)</del>         # Recursively implemented Bareiss' algorithm as per Deanna Richelle Leggett's         # thesis http://www.math.usm.edu/perry/Research/Thesis_DRL.pdf         def bareiss(mat, cumm=1):


return mat[0, 0]              # find a pivot and extract the remaining matrix            # XXX should use `_find_reasonable_pivot`.  Blocked by issue #12362            pivot_pos, pivot_val, _, _ = _find_pivot(mat[:, 0])            # With the default iszerofunc, _find_reasonable_pivot slows down            # the computation by the factor of 2.5 in one test.            # Relevant issues: #10279 and #13877.            pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0],                                         iszerofunc=_is_zero_after_expand_mul)             if pivot_pos == None:                 return S.Zero diff --git a/sympy/utilities/randtest.py b/sympy/utilities/randtest.py-- a/sympy/utilities/randtest.py++ b/sympy/utilities/randtest.py


from sympy.core.compatibility import is_sequence, as_int  def random_complex_number(a=2, b=-1, c=3, d=1, rational=False):def random_complex_number(a=2, b=-1, c=3, d=1, rational=False, tolerance=None):     """     Return a random complex number.      To reduce chance of hitting branch cuts or anything, we guarantee     b <= Im z <= d, a <= Re z <= c    When rational is True, a rational approximation to a random number    is obtained within specified tolerance, if any.     """     A, B = uniform(a, c), uniform(b, d)     if not rational:         return A + I*B    return nsimplify(A, rational=True) + I*nsimplify(B, rational=True)    return (nsimplify(A, rational=True, tolerance=tolerance) +        I*nsimplify(B, rational=True, tolerance=tolerance))   def verify_numerically(f, g, z=None, tol=1.0e-6, a=2, b=-1, c=3, d=1):


if p is not False:             dict = {p[0]: p[1]}         else:            dict = Integer(self).factors(limit=2**15)            dict = Integer(b_pos).factors(limit=2**15)          # now process the dict of factors        if self.is_negative:            dict[-1] = 1         out_int = 1  # integer part         out_rad = 1  # extracted radicals         sqr_int = 1


break         for k, v in sqr_dict.items():             sqr_int *= k**(v//sqr_gcd)        if sqr_int == self and out_int == 1 and out_rad == 1:        if sqr_int == b_pos and out_int == 1 and out_rad == 1:             result = None         else:             result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q))            if self.is_negative:                result *= Pow(S.NegativeOne, expt)         return result      def _eval_is_prime(self):


"exp": "exp",     "erf": "erf",     "Abs": "abs",    "conjugate": "conjg"    "conjugate": "conjg",    "Max": "max",    "Min": "min" }  diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py-- a/sympy/printing/octave.py++ b/sympy/printing/octave.py


"laguerre": "laguerreL",     "li": "logint",     "loggamma": "gammaln",<ins>    "Max": "max",    "Min": "min",</ins>     "polygamma": "psi",     "Shi": "sinhint",     "Si": "sinint",


# assignment (if False).  FIXME: this should be looked a more carefully     # for Octave. <ins></ins>     def __init__(self, settings={}):         super(OctaveCodePrinter, self).__init__(settings)         self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))


return "lambertw(" + args + ")"  <ins>    def _nested_binary_math_func(self, expr):        return '{name}({arg1}, {arg2})'.format(            name=self.known_functions[expr.__class__.__name__],            arg1=self._print(expr.args[0]),            arg2=self._print(expr.func(*expr.args[1:]))            )    _print_Max = _print_Min = _nested_binary_math_func</ins>     def _print_Piecewise(self, expr):         if expr.args[-1].cond != True:             # We need the last conditional to be a True, otherwise the resulting


changed = False             for b, e in c_powers:                 if e.is_zero:<ins>                    # canceling out infinities yields NaN                    if (b.is_Add or b.is_Mul) and any(infty in b.args                        for infty in (S.ComplexInfinity, S.Infinity,                                      S.NegativeInfinity)):                        return [S.NaN], [], None</ins>                     continue                 if e is S.One:                     if b.is_Number:


"order": None,         "full_prec": "auto",         "sympy_integers": False,<ins>        "abbrev": False,</ins>     }      _relationals = dict()


return r' \ '.join(self._print(set) for set in expr.args)      def _print_Quantity(self, expr):<ins>        if self._settings.get("abbrev", False):            return "%s" % expr.abbrev</ins>         return "%s" % expr.name      def _print_Quaternion(self, expr):


"""Returns the expression as a string.      For large expressions where speed is a concern, use the setting    order='none'.    order='none'. If abbrev=True setting is used then units are printed in    abbreviated form.      Examples     ========


else:             printset = tuple(s)         return (r"\left\["        return (r"\left["               + r", ".join(self._print(el) for el in printset)              + r"\right\]")              + r"\right]")      _print_SeqPer = _print_SeqFormula     _print_SeqAdd = _print_SeqFormula


matrix_tensor_product ) <ins></ins> __all__ = [     'TensorProduct',     'tensor_product_simp'


"""     # TODO: This won't work with Muls that have other composites of    # TensorProducts, like an Add, Pow, Commutator, etc.    # TensorProducts, like an Add, Commutator, etc.     # TODO: This only works for the equivalent of single Qbit gates.     if not isinstance(e, Mul):         return e     c_part, nc_part = e.args_cnc()     n_nc = len(nc_part)    if n_nc == 0 or n_nc == 1:    if n_nc == 0:        return e    elif n_nc == 1:        if isinstance(nc_part[0], Pow):            return  Mul(*c_part) * tensor_product_simp_Pow(nc_part[0])         return e     elif e.has(TensorProduct):         current = nc_part[0]         if not isinstance(current, TensorProduct):            raise TypeError('TensorProduct expected, got: %r' % current)            if isinstance(current, Pow):                if isinstance(current.base, TensorProduct):                    current = tensor_product_simp_Pow(current)            else:                raise TypeError('TensorProduct expected, got: %r' % current)         n_terms = len(current.args)         new_args = list(current.args)         for next in nc_part[1:]:


for i in range(len(new_args)):                     new_args[i] = new_args[i] * next.args[i]             else:                # this won't quite work as we don't want next in the                # TensorProduct                for i in range(len(new_args)):                    new_args[i] = new_args[i] * next                if isinstance(next, Pow):                    if isinstance(next.base, TensorProduct):                        new_tp = tensor_product_simp_Pow(next)                        for i in range(len(new_args)):                            new_args[i] = new_args[i] * new_tp.args[i]                    else:                        raise TypeError('TensorProduct expected, got: %r' % next)                else:                    raise TypeError('TensorProduct expected, got: %r' % next)             current = next         return Mul(*c_part) * TensorProduct(*new_args)    elif e.has(Pow):        new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ]        return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args))     else:         return e def tensor_product_simp_Pow(e):    """Evaluates ``Pow`` expressions whose base is ``TensorProduct``"""    if not isinstance(e, Pow):        return e    if isinstance(e.base, TensorProduct):        return TensorProduct(*[ b**e.exp for b in e.base.args])    else:        return e  def tensor_product_simp(e, **hints):     """Try to simplify and combine TensorProducts.


if isinstance(e, Add):         return Add(*[tensor_product_simp(arg) for arg in e.args])     elif isinstance(e, Pow):        return tensor_product_simp(e.base) ** e.exp        if isinstance(e.base, TensorProduct):            return tensor_product_simp_Pow(e)        else:            return tensor_product_simp(e.base) ** e.exp     elif isinstance(e, Mul):         return tensor_product_simp_Mul(e)     elif isinstance(e, Commutator):


def _print_Mul(self, expr):         # print complex numbers nicely in Octave         if (expr.is_number and expr.is_imaginary and                expr.as_coeff_Mul()[0].is_integer):                (S.ImaginaryUnit*expr).is_Integer):             return "%si" % self._print(-S.ImaginaryUnit*expr)          # cribbed from str.py


break         return integrate(leading_term, *self.args[1:])     def as_sum(self, n, method="midpoint"):    def as_sum(self, n=None, method="midpoint", evaluate=True):         """        Approximates the definite integral by a sum.        Approximates a definite integral by a sum.         method ... one of: left, right, midpoint, trapezoid        Arguments        ---------        n            The number of subintervals to use, optional.        method            One of: 'left', 'right', 'midpoint', 'trapezoid'.        evaluate            If False, returns an unevaluated Sum expression. The default            is True, evaluate the sum.         These are all basically the rectangle method [1], the only difference        is where the function value is taken in each interval to define the        rectangle.        These methods of approximate integration are described in [1].         [1] http://en.wikipedia.org/wiki/Rectangle_method        [1] https://en.wikipedia.org/wiki/Riemann_sum#Methods          Examples         ========          >>> from sympy import sin, sqrt        >>> from sympy.abc import x        >>> from sympy.abc import x, n         >>> from sympy.integrals import Integral         >>> e = Integral(sin(x), (x, 3, 7))         >>> e


>>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == _         True         All but the trapexoid method may be used when dealing with a function        with a discontinuity. Here, the discontinuity at x = 0 can be avoided        by using the midpoint or right-hand method:        Here, the discontinuity at x = 0 can be avoided by using the        midpoint or right-hand method:          >>> e = Integral(1/sqrt(x), (x, 0, 1))         >>> e.as_sum(5).n(4)


2.000          The left- or trapezoid method will encounter the discontinuity and        return oo:        return infinity:          >>> e.as_sum(5, 'left')        oo        >>> e.as_sum(5, 'trapezoid')        oo        zoo        The number of intervals can be symbolic. If omitted, a dummy symbol        will be used for it.        >>> e = Integral(x**2, (x, 0, 2))        >>> e.as_sum(n, 'right').expand()        8/3 + 4/n + 4/(3*n**2)        This shows that the midpoint rule is more accurate, as its error        term decays as the square of n:        >>> e.as_sum(method='midpoint').expand()        8/3 - 2/(3*_n**2)        A symbolic sum is returned with evaluate=False:        >>> e.as_sum(n, 'midpoint', evaluate=False)        2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n          See Also         ========


Integral.doit : Perform the integration using any hints         """         from sympy.concrete.summations import Sum         limits = self.limits         if len(limits) > 1:             raise NotImplementedError(                 "Multidimensional midpoint rule not implemented yet")         else:             limit = limits[0]            if len(limit) != 3:                raise ValueError("Expecting a definite integral.")        if n <= 0:            raise ValueError("n must be > 0")        if n == oo:            raise NotImplementedError("Infinite summation not yet implemented")        sym, lower_limit, upper_limit = limit        dx = (upper_limit - lower_limit)/n        if method == 'trapezoid':            l = self.function.limit(sym, lower_limit)            r = self.function.limit(sym, upper_limit, "-")            result = (l + r)/2            for i in range(1, n):                x = lower_limit + i*dx                result += self.function.subs(sym, x)            return result*dx        elif method not in ('left', 'right', 'midpoint'):            raise NotImplementedError("Unknown method %s" % method)        result = 0        for i in range(n):            if method == "midpoint":                xi = lower_limit + i*dx + dx/2            elif method == "left":                xi = lower_limit + i*dx                if i == 0:                    result = self.function.limit(sym, lower_limit)                    continue            elif method == "right":                xi = lower_limit + i*dx + dx                if i == n:                    result += self.function.limit(sym, upper_limit, "-")                    continue            result += self.function.subs(sym, xi)        return result*dx            if (len(limit) != 3 or limit[1].is_finite is False or                limit[2].is_finite is False):                raise ValueError("Expecting a definite integral over "                                  "a finite interval.")        if n is None:            n = Dummy('n', integer=True, positive=True)        else:            n = sympify(n)        if (n.is_positive is False or n.is_integer is False or            n.is_finite is False):            raise ValueError("n must be a positive integer, got %s" % n)        x, a, b = limit        dx = (b - a)/n        k = Dummy('k', integer=True, positive=True)        f = self.function        if method == "left":            result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))        elif method == "right":            result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))        elif method == "midpoint":            result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))        elif method == "trapezoid":            result = dx*((f.subs(x, a) + f.subs(x, b))/2 +                Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))        else:            raise ValueError("Unknown method %s" % method)        return result.doit() if evaluate else result      def _sage_(self):         import sage.all as sage


if (ne is S.One):                     return Rational(self.q, self.p)                 if self.is_negative:                    if expt.q != 1:                        return -(S.NegativeOne)**((expt.p % expt.q) /                               S(expt.q))*Rational(self.q, -self.p)**ne                    else:                        return S.NegativeOne**ne*Rational(self.q, -self.p)**ne                    return S.NegativeOne**expt*Rational(self.q, -self.p)**ne                 else:                     return Rational(self.q, self.p)**ne             if expt is S.Infinity:  # -oo already caught by test for negative


# invert base and change sign on exponent             ne = -expt             if self.is_negative:                if expt.q != 1:                    return -(S.NegativeOne)**((expt.p % expt.q) /                            S(expt.q))*Rational(1, -self)**ne                else:                    return (S.NegativeOne)**ne*Rational(1, -self)**ne                    return S.NegativeOne**expt*Rational(1, -self)**ne             else:                 return Rational(1, self.p)**ne         # see if base is a perfect root, sqrt(4) --> 2


from sympy.core.compatibility import is_sequence, reduce, string_types from sympy.core.expr import Expr from sympy.core.mod import Mod<ins>from sympy.core.numbers import Exp1from sympy.core.singleton import S</ins> from sympy.core.symbol import Symbol from sympy.core.sympify import CantSympify, sympify from sympy.functions.elementary.exponential import ExpBase


return reduce(add, list(map(_rebuild, expr.args)))             elif expr.is_Mul:                 return reduce(mul, list(map(_rebuild, expr.args)))            elif expr.is_Pow or isinstance(expr, ExpBase):            elif expr.is_Pow or isinstance(expr, (ExpBase, Exp1)):                 b, e = expr.as_base_exp()                 # look for bg**eg whose integer power may be b**e                choices = tuple((gen, bg, eg) for gen, (bg, eg) in powers                    if bg == b and Mod(e, eg) == 0)                if choices:                    gen, bg, eg = choices[0]                    return mapping.get(gen)**(e/eg)                elif e.is_Integer:                    return _rebuild(expr.base)**int(expr.exp)                for gen, (bg, eg) in powers:                    if bg == b and Mod(e, eg) == 0:                        return mapping.get(gen)**int(e/eg)                if e.is_Integer and e is not S.One:                    return _rebuild(b)**int(e)              try:                 return domain.convert(expr)


from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.concrete.expr_with_intlimits import ExprWithIntLimits<ins>from sympy.core.exprtools import factor_terms</ins> from sympy.functions.elementary.exponential import exp, log from sympy.polys import quo, roots from sympy.simplify import powsimp


return poly.LC()**(n - a + 1) * A * B          elif term.is_Add:            p, q = term.as_numer_denom()            q = self._eval_product(q, (k, a, n))            if q.is_Number:                # There is expression, which couldn't change by                # as_numer_denom(). E.g. n**(2/3) + 1 --> (n**(2/3) + 1, 1).                # We have to catch this case.                from sympy.concrete.summations import Sum                p = exp(Sum(log(p), (k, a, n)))            else:                p = self._eval_product(p, (k, a, n))            return p / q            factored = factor_terms(term, fraction=True)            if factored.is_Mul:                return self._eval_product(factored, (k, a, n))          elif term.is_Mul:             exclude, include = [], []


for k in list(log1.keys()):             log1[Mul(*k)] = log(logcombine(Mul(*[                 l.args[0]**Mul(*c) for c, l in log1.pop(k)]),                force=force))                force=force), evaluate=False)          # logs that have oppositely signed coefficients can divide         for k in ordered(list(log1.keys())):