Question: return AssocOp._matches_commutative(self, expr, repl_dict, old)         elif self.is_commutative is not expr.is_commutative:             return None        # Proceed only if both both expressions are non-commutative         c1, nc1 = self.args_cnc()         c2, nc2 = expr.args_cnc()        repl_dict = repl_dict.copy()        if c1:            if not c2:                c2 = [1]            a = self.func(*c1)            if isinstance(a, AssocOp):                repl_dict = a._matches_commutative(self.func(*c2), repl_dict, old)            else:                repl_dict = a.matches(self.func(*c2), repl_dict)        if repl_dict:            a = self.func(*nc1)            if isinstance(a, self.func):                repl_dict = a._matches(self.func(*nc2), repl_dict)            else:                repl_dict = a.matches(self.func(*nc2), repl_dict)        c1, c2 = [c or [1] for c in [c1, c2]]        # TODO: Should these be self.func?        comm_mul_self = Mul(*c1)        comm_mul_expr = Mul(*c2)        repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)        # If the commutative arguments didn't match and aren't equal, then        # then the expression as a whole doesn't match        if repl_dict is None and c1 != c2:            return None        # Now match the non-commutative arguments, expanding powers to        # multiplications        nc1 = Mul._matches_expand_pows(nc1)        nc2 = Mul._matches_expand_pows(nc2)        repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)         return repl_dict or None     def _matches(self, expr, repl_dict={}):        # weed out negative one prefixes#        from sympy import Wild        sign = 1        a, b = self.as_two_terms()        if a is S.NegativeOne:            if b.is_Mul:                sign = -sign    @staticmethod    def _matches_expand_pows(arg_list):        new_args = []        for arg in arg_list:            if arg.is_Pow and arg.exp > 0:                new_args.extend([arg.base] * arg.exp)             else:                # the remainder, b, is not a Mul anymore                return b.matches(-expr, repl_dict)        expr = sympify(expr)        if expr.is_Mul and expr.args[0] is S.NegativeOne:            expr = -expr            sign = -sign        if not expr.is_Mul:            # expr can only match if it matches b and a matches +/- 1            if len(self.args) == 2:                # quickly test for equality                if b == expr:                    return a.matches(Rational(sign), repl_dict)                # do more expensive match                dd = b.matches(expr, repl_dict)                if dd is None:                    return None                dd = a.matches(Rational(sign), dd)                return dd            return None                new_args.append(arg)        return new_args         d = repl_dict.copy()    @staticmethod    def _matches_noncomm(nodes, targets, repl_dict={}):        """Non-commutative multiplication matcher.         # weed out identical terms        pp = list(self.args)        ee = list(expr.args)        for p in self.args:            if p in expr.args:                ee.remove(p)                pp.remove(p)        `nodes` is a list of symbols within the matcher multiplication        expression, while `targets` is a list of arguments in the        multiplication expression being matched against.        """        # List of possible future states to be considered        agenda = []        # The current matching state, storing index in nodes and targets        state = (0, 0)        node_ind, target_ind = state        # Mapping between wildcard indices and the index ranges they match        wildcard_dict = {}        repl_dict = repl_dict.copy()         # only one symbol left in pattern -> match the remaining expression        if len(pp) == 1 and isinstance(pp[0], Wild):            if len(ee) == 1:                d[pp[0]] = sign * ee[0]        while target_ind < len(targets) and node_ind < len(nodes):            node = nodes[node_ind]            if node.is_Wild:                Mul._matches_add_wildcard(wildcard_dict, state)            states_matches = Mul._matches_new_states(wildcard_dict, state,                                                     nodes, targets)            if states_matches:                new_states, new_matches = states_matches                agenda.extend(new_states)                if new_matches:                    for match in new_matches:                        repl_dict[match] = new_matches[match]            if not agenda:                return None             else:                d[pp[0]] = sign * expr.func(*ee)            return d                state = agenda.pop()                node_ind, target_ind = state        return repl_dict         if len(ee) != len(pp):    @staticmethod    def _matches_add_wildcard(dictionary, state):        node_ind, target_ind = state        if node_ind in dictionary:            begin, end = dictionary[node_ind]            dictionary[node_ind] = (begin, target_ind)        else:            dictionary[node_ind] = (target_ind, target_ind)    @staticmethod    def _matches_new_states(dictionary, state, nodes, targets):        node_ind, target_ind = state        node = nodes[node_ind]        target = targets[target_ind]        # Don't advance at all if we've exhausted the targets but not the nodes        if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:             return None         for p, e in zip(pp, ee):            d = p.xreplace(d).matches(e, d)            if d is None:        if node.is_Wild:            match_attempt = Mul._matches_match_wilds(dictionary, node_ind,                                                     nodes, targets)            if match_attempt:                # If the same node has been matched before, don't return                # anything if the current match is diverging from the previous                # match                other_node_inds = Mul._matches_get_other_nodes(dictionary,                                                               nodes, node_ind)                for ind in other_node_inds:                    other_begin, other_end = dictionary[ind]                    curr_begin, curr_end = dictionary[node_ind]                    other_targets = targets[other_begin:other_end + 1]                    current_targets = targets[curr_begin:curr_end + 1]                    for curr, other in zip(current_targets, other_targets):                        if curr != other:                            return None                # A wildcard node can match more than one target, so only the                # target index is advanced                new_state = [(node_ind, target_ind + 1)]                # Only move on to the next node if there is one                if node_ind < len(nodes) - 1:                    new_state.append((node_ind + 1, target_ind + 1))                return new_state, match_attempt        else:            # If we're not at a wildcard, then make sure we haven't exhausted            # nodes but not targets, since in this case one node can only match            # one target            if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:                return None            match_attempt = node.matches(target)            if match_attempt:                return [(node_ind + 1, target_ind + 1)], match_attempt            elif node == target:                return [(node_ind + 1, target_ind + 1)], None            else:                 return None        return d    @staticmethod    def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):        """Determine matches of a wildcard with sub-expression in `target`."""        wildcard = nodes[wildcard_ind]        begin, end = dictionary[wildcard_ind]        terms = targets[begin:end + 1]        # TODO: Should this be self.func?        mul = Mul(*terms) if len(terms) > 1 else terms[0]        return wildcard.matches(mul)    @staticmethod    def _matches_get_other_nodes(dictionary, nodes, node_ind):        """Find other wildcards that may have already been matched."""        other_node_inds = []        for ind in dictionary:            if nodes[ind] == nodes[node_ind]:                other_node_inds.append(ind)        return other_node_inds      @staticmethod     def _combine_inverse(lhs, rhs):

Match doesn't respect matrix non-commutativity doesn't obey the commutativity of matrix expressions when matching scalars between two expressions. As a demonstration: should be , since the associated matrix multiplications are in a different order (and so not indentical).


Question: elif isinstance(arg, SetExpr):             return arg._eval_func(cls)         elif arg.is_Mul:            if arg.is_number or arg.is_Symbol:                coeff = arg.coeff(S.Pi*S.ImaginaryUnit)                if coeff:                    if ask(Q.integer(2*coeff)):                        if ask(Q.even(coeff)):                            return S.One                        elif ask(Q.odd(coeff)):                            return S.NegativeOne                        elif ask(Q.even(coeff + S.Half)):                            return -S.ImaginaryUnit                        elif ask(Q.odd(coeff + S.Half)):                            return S.ImaginaryUnit            coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)            if coeff:                if (2*coeff).is_integer:                    if coeff.is_even:                        return S.One                    elif coeff.is_odd:                        return S.NegativeOne                    elif (coeff + S.Half).is_even:                        return -S.ImaginaryUnit                    elif (coeff + S.Half).is_odd:                        return S.ImaginaryUnit                elif coeff.is_Rational:                    ncoeff = coeff % 2 # restrict to [0, 2pi)                    if ncoeff > 1: # restrict to (-pi, pi]                        ncoeff -= 2                    if ncoeff != coeff:                        return cls(ncoeff*S.Pi*S.ImaginaryUnit)              # Warning: code in risch.py will be very sensitive to changes             # in this (see DifferentialExtension).

exp doesn't simplify based on its periodicity In current master, doesn't use its periodicity to automatically reduce its argument, not even for purely imaginary arguments:


Question: elif arg.is_Add:             out = []             add = []            argchanged = False             for a in arg.args:                 if a is S.One:                     add.append(a)                     continue                 newa = cls(a)                 if isinstance(newa, cls):                    add.append(a)                    if newa.args[0] != a:                        add.append(newa.args[0])                        argchanged = True                    else:                        add.append(a)                 else:                     out.append(newa)            if out:            if out or argchanged:                 return Mul(*out)*cls(Add(*add), evaluate=False)          elif isinstance(arg, MatrixBase):diff --git a/sympy/physics/matrices.py b/sympy/physics/matrices.py-- a/sympy/physics/matrices.py++ b/sympy/physics/matrices.py


Question: >>> mdft(3)     Matrix([     [sqrt(3)/3,                sqrt(3)/3,                sqrt(3)/3],    [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(-4*I*pi/3)/3],    [sqrt(3)/3, sqrt(3)*exp(-4*I*pi/3)/3, sqrt(3)*exp(-8*I*pi/3)/3]])    [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3,  sqrt(3)*exp(2*I*pi/3)/3],    [sqrt(3)/3,  sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]])     """     mat = [[None for x in range(n)] for y in range(n)]     base = exp(-2*pi*I/n)


Question: from sympy.core import Add, S from sympy.core.evalf import get_integer_part, PrecisionExhausted from sympy.core.function import Functionfrom sympy.core.logic import fuzzy_or from sympy.core.numbers import Integerfrom sympy.core.relational import Gt, Lt, Ge, Lefrom sympy.core.relational import Gt, Lt, Ge, Le, Relational from sympy.core.symbol import Symbolfrom sympy.core.sympify import _sympify   ###############################################################################

frac(zoo) gives TypeError Not sure what should happen, but not this. I am trying to cover these lines in a test: Clearly, they are covered by calling since the comes from that line, but I do not really want an exception...


Question: def __le__(self, other):         if self.args[0] == other and other.is_real:             return S.true<ins>        if other is S.Infinity and self.is_finite:            return S.true</ins>         return Le(self, other, evaluate=False)      def __gt__(self, other):


Question: def __ge__(self, other):         if self.args[0] == other and other.is_real:             return S.true<ins>        if other is S.NegativeInfinity and self.is_real:            return S.true</ins>         return Ge(self, other, evaluate=False)


Question: if arg is S.NaN:                     return S.NaN                 elif arg is S.ComplexInfinity:                    return None                    return S.NaN                 else:                     return arg - floor(arg)             return cls(arg, evaluate=False)


Question: if (self.rewrite(floor) == other) or \                     (self.rewrite(ceiling) == other):                 return S.true            # Check if other < 0            if other.is_extended_negative:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return S.false    def _eval_is_finite(self):        return True    def _eval_is_real(self):        return self.args[0].is_extended_real    def _eval_is_imaginary(self):        return self.args[0].is_imaginary    def _eval_is_integer(self):        return self.args[0].is_integer    def _eval_is_zero(self):        return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])    def _eval_is_negative(self):        return False    def __ge__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other <= 0            if other.is_extended_nonpositive:                return S.true            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return not(res)        return Ge(self, other, evaluate=False)    def __gt__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other < 0            res = self._value_one_or_more(other)            if res is not None:                return not(res)            # Check if other >= 1            if other.is_extended_negative:                return S.true        return Gt(self, other, evaluate=False)    def __le__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other < 0            if other.is_extended_negative:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return res        return Le(self, other, evaluate=False)    def __lt__(self, other):        if self.is_extended_real:            other = _sympify(other)            # Check if other <= 0            if other.is_extended_nonpositive:                return S.false            # Check if other >= 1            res = self._value_one_or_more(other)            if res is not None:                return res        return Lt(self, other, evaluate=False)    def _value_one_or_more(self, other):        if other.is_extended_real:            if other.is_number:                res = other >= 1                if res and not isinstance(res, Relational):                    return S.true            if other.is_integer and other.is_positive:                return S.truediff --git a/sympy/printing/latex.py b/sympy/printing/latex.py-- a/sympy/printing/latex.py++ b/sympy/printing/latex.py


Question: def _print_UniversalSet(self, expr):         return r"\mathbb{U}" <ins>    def _print_frac(self, expr, exp=None):        if exp is None:            return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0])        else:            return r"\operatorname{frac}{\left(%s\right)}^{%s}" % (                    self._print(expr.args[0]), self._print(exp))</ins>     def _print_tuple(self, expr):         if self._settings['decimal_separator'] =='comma':             return r"\left( %s\right)" % \


Question: year, years, tropical_year,     G, gravitational_constant,     c, speed_of_light,<ins>    elementary_charge,</ins>     Z0,     hbar,     planck,

Incorrect value for hbar in The numerical value given for hbar differs from the CODATA recommended one of: .


Question: >>> from sympy.physics import units as u     >>> u.find_unit('charge')    ['C', 'coulomb', 'coulombs', 'planck_charge']    ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']     >>> u.find_unit(u.charge)    ['C', 'coulomb', 'coulombs', 'planck_charge']    ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']     >>> u.find_unit("ampere")     ['ampere', 'amperes']     >>> u.find_unit('volt')diff --git a/sympy/physics/units/definitions.py b/sympy/physics/units/definitions.py-- a/sympy/physics/units/definitions.py++ b/sympy/physics/units/definitions.py


Question: #### CONSTANTS ####  # Newton constant# REF: NIST SP 959 (June 2019) G = gravitational_constant = Quantity("gravitational_constant", abbrev="G") gravitational_constant.set_dimension(length**3*mass**-1*time**-2)gravitational_constant.set_scale_factor(6.67408e-11*m**3/(kg*s**2))gravitational_constant.set_scale_factor(6.67430e-11*m**3/(kg*s**2))  # speed of light c = speed_of_light = Quantity("speed_of_light", abbrev="c") speed_of_light.set_dimension(velocity) speed_of_light.set_scale_factor(299792458*meter/second) # Reduced Planck constanthbar = Quantity("hbar", abbrev="hbar")hbar.set_dimension(action)hbar.set_scale_factor(1.05457266e-34*joule*second)# elementary charge# REF: NIST SP 959 (June 2019)elementary_charge = Quantity("elementary_charge", abbrev="e")elementary_charge.set_dimension(charge)elementary_charge.set_scale_factor(1.602176634e-19*coulomb)  # Planck constant# REF: NIST SP 959 (June 2019) planck = Quantity("planck", abbrev="h") planck.set_dimension(action)planck.set_scale_factor(2*pi*hbar)planck.set_scale_factor(6.62607015e-34*joule*second)# Reduced Planck constant# REF: NIST SP 959 (June 2019)hbar = Quantity("hbar", abbrev="hbar")hbar.set_dimension(action)hbar.set_scale_factor(planck / (2 * pi))  # Electronvolt# REF: NIST SP 959 (June 2019) eV = electronvolt = electronvolts = Quantity("electronvolt", abbrev="eV") electronvolt.set_dimension(energy)electronvolt.set_scale_factor(1.60219e-19*joule)electronvolt.set_scale_factor(1.602176634e-19*joule)  # Avogadro number# REF: NIST SP 959 (June 2019) avogadro_number = Quantity("avogadro_number") avogadro_number.set_dimension(One)avogadro_number.set_scale_factor(6.022140857e23)avogadro_number.set_scale_factor(6.02214076e23)  # Avogadro constant avogadro = avogadro_constant = Quantity("avogadro_constant")


Question: avogadro_constant.set_scale_factor(avogadro_number / mol)  # Boltzmann constant# REF: NIST SP 959 (June 2019) boltzmann = boltzmann_constant = Quantity("boltzmann_constant") boltzmann_constant.set_dimension(energy/temperature)boltzmann_constant.set_scale_factor(1.38064852e-23*joule/kelvin)boltzmann_constant.set_scale_factor(1.380649e-23*joule/kelvin)  # Stefan-Boltzmann constant# REF: NIST SP 959 (June 2019) stefan = stefan_boltzmann_constant = Quantity("stefan_boltzmann_constant") stefan_boltzmann_constant.set_dimension(energy*time**-1*length**-2*temperature**-4)stefan_boltzmann_constant.set_scale_factor(5.670367e-8*joule/(s*m**2*kelvin**4))stefan_boltzmann_constant.set_scale_factor(pi**2 * boltzmann_constant**4 / (60 * hbar**3 * speed_of_light ** 2))  # Atomic mass# REF: NIST SP 959 (June 2019) amu = amus = atomic_mass_unit = atomic_mass_constant = Quantity("atomic_mass_constant") atomic_mass_constant.set_dimension(mass)atomic_mass_constant.set_scale_factor(1.660539040e-24*gram)atomic_mass_constant.set_scale_factor(1.66053906660e-24*gram)  # Molar gas constant# REF: NIST SP 959 (June 2019) R = molar_gas_constant = Quantity("molar_gas_constant", abbrev="R") molar_gas_constant.set_dimension(energy/(temperature * amount_of_substance))molar_gas_constant.set_scale_factor(8.3144598*joule/kelvin/mol)molar_gas_constant.set_scale_factor(boltzmann_constant * avogadro_constant)  # Faraday constant faraday_constant = Quantity("faraday_constant") faraday_constant.set_dimension(charge/amount_of_substance)faraday_constant.set_scale_factor(96485.33289*C/mol)faraday_constant.set_scale_factor(elementary_charge * avogadro_constant)  # Josephson constant josephson_constant = Quantity("josephson_constant", abbrev="K_j") josephson_constant.set_dimension(frequency/voltage)josephson_constant.set_scale_factor(483597.8525e9*hertz/V)josephson_constant.set_scale_factor(0.5 * planck / elementary_charge)  # Von Klitzing constant von_klitzing_constant = Quantity("von_klitzing_constant", abbrev="R_k") von_klitzing_constant.set_dimension(voltage/current)von_klitzing_constant.set_scale_factor(25812.8074555*ohm)von_klitzing_constant.set_scale_factor(hbar / elementary_charge ** 2)  # Acceleration due to gravity (on the Earth surface) gee = gees = acceleration_due_to_gravity = Quantity("acceleration_due_to_gravity", abbrev="g")diff --git a/sympy/physics/units/util.py b/sympy/physics/units/util.py-- a/sympy/physics/units/util.py++ b/sympy/physics/units/util.py


Question: >>> from sympy.physics.units import speed_of_light, meter, gram, second, day     >>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant     >>> from sympy.physics.units import kilometer, centimeter<ins>    >>> from sympy.physics.units import gravitational_constant, hbar</ins>     >>> from sympy.physics.units import convert_to     >>> convert_to(mile, kilometer)     25146*kilometer/15625


Question: >>> convert_to(3*newton, kilogram*meter/second**2)     3*kilogram*meter/second**2     >>> convert_to(atomic_mass_constant, gram)    1.66053904e-24*gram    1.660539060e-24*gram      Conversion to multiple units:


Question: >>> from sympy.physics.units import gravitational_constant, hbar     >>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n()    7.62950196312651e-20*gravitational_constant**(-0.5)*hbar**0.5*speed_of_light**0.5    7.62963085040767e-20*gravitational_constant**(-0.5)*hbar**0.5*speed_of_light**0.5      """     if not isinstance(target_units, (Iterable, Tuple)):


Question: else:             return self._print(item) <ins>    def parenthesize_super(self, s):        """ Parenthesize s if there is a superscript in s"""        if "^" in s:            return r"\left({}\right)".format(s)        return s    def embed_super(self, s):        """ Embed s in {} if there is a superscript in s"""        if "^" in s:            return "{{{}}}".format(s)        return s</ins>     def doprint(self, expr):         tex = Printer.doprint(self, expr)

Latex printing issue on derivatives with superscripted symbols When I display the derivatives of second-or-more order with superscipted symbols, it gives wrong latex expression and fails to print correctly with IPython environment. For example, this gives instead of nice latex formula. I figure that this is because x^{}^{2} is wrong latex expression. It should be x^{2}, and thus I report it as an issue.


Question: if num == 1:                 tex += r"%s %s" % (diff_symbol, self._print(x))             else:                tex += r"%s %s^{%s}" % (diff_symbol, self._print(x), num)                tex += r"%s %s^{%s}" % (diff_symbol,                                        self.parenthesize_super(self._print(x)),                                        num)          if dim == 1:             tex = r"\frac{%s}{%s}" % (diff_symbol, tex)


Question: if isinstance(e.args[0], Implies):             return self._print_Implies(e.args[0], r"\not\Rightarrow")         if (e.args[0].is_Boolean):            return r"\neg (%s)" % self._print(e.args[0])            return r"\neg \left(%s\right)" % self._print(e.args[0])         else:             return r"\neg %s" % self._print(e.args[0])


Question: else:             return r <ins>    def _eval_is_negative(self):        return self.args[0].is_negative    def _eval_is_nonnegative(self):        return self.args[0].is_nonnegative</ins>     def _eval_rewrite_as_ceiling(self, arg, **kwargs):         return -ceiling(-arg)

ceiling(pos) 0 should be true Also, shouldn't , and evaluate to True, too?


Question: return S.true      def __le__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] < other + 1            if other.is_number and other.is_real:                return self.args[0] < ceiling(other)         if self.args[0] == other and other.is_real:             return S.true         if other is S.Infinity and self.is_finite:             return S.true         return Le(self, other, evaluate=False)     def __ge__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] >= other            if other.is_number and other.is_real:                return self.args[0] >= ceiling(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true        return Ge(self, other, evaluate=False)     def __gt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] >= other + 1            if other.is_number and other.is_real:                return self.args[0] >= ceiling(other)         if self.args[0] == other and other.is_real:             return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true         return Gt(self, other, evaluate=False)     def __lt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] < other            if other.is_number and other.is_real:                return self.args[0] < ceiling(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.Infinity and self.is_finite:            return S.true        return Lt(self, other, evaluate=False)  class ceiling(RoundFunction):     """


Question: def _eval_rewrite_as_frac(self, arg, **kwargs):         return arg + frac(-arg) <ins>    def _eval_is_positive(self):        return self.args[0].is_positive    def _eval_is_nonpositive(self):        return self.args[0].is_nonpositive</ins>     def _eval_Eq(self, other):         if isinstance(self, ceiling):             if (self.rewrite(floor) == other) or \


Question: return S.true      def __lt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] <= other - 1            if other.is_number and other.is_real:                return self.args[0] <= floor(other)         if self.args[0] == other and other.is_real:             return S.false        if other is S.Infinity and self.is_finite:            return S.true         return Lt(self, other, evaluate=False)     def __gt__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] > other            if other.is_number and other.is_real:                return self.args[0] > floor(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.NegativeInfinity and self.is_finite:            return S.true        return Gt(self, other, evaluate=False)     def __ge__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] > other - 1            if other.is_number and other.is_real:                return self.args[0] > floor(other)         if self.args[0] == other and other.is_real:             return S.true        if other is S.NegativeInfinity and self.is_real:        if other is S.NegativeInfinity and self.is_finite:             return S.true         return Ge(self, other, evaluate=False)     def __le__(self, other):        other = S(other)        if self.args[0].is_real:            if other.is_integer:                return self.args[0] <= other            if other.is_number and other.is_real:                return self.args[0] <= floor(other)        if self.args[0] == other and other.is_real:            return S.false        if other is S.Infinity and self.is_finite:            return S.true        return Le(self, other, evaluate=False)  class frac(Function):     r"""Represents the fractional part of x


Question: def rad_rationalize(num, den):     """     Rationalize num/den by removing square roots in the denominator;    num and den are sum of terms whose squares are rationals    num and den are sum of terms whose squares are positive rationals.      Examples     ========

sqrtdenest raises IndexError If an expression cannot be denested it should be returned unchanged. IndexError fixed for sqrtdenest. Now if the expression can't be denested, it will be returned unchanged. Old Result: New Result:


Question: def split_surds(expr):     """    split an expression with terms whose squares are rationals    Split an expression with terms whose squares are positive rationals     into a sum of terms whose surds squared have gcd equal to g    and a sum of terms with surds squared prime with g    and a sum of terms with surds squared prime with g.      Examples     ========diff --git a/sympy/simplify/sqrtdenest.py b/sympy/simplify/sqrtdenest.py-- a/sympy/simplify/sqrtdenest.py++ b/sympy/simplify/sqrtdenest.py


Question: res = (p, S.Zero, S.Zero)     elif p.is_Add:         pargs = sorted(p.args, key=default_sort_key)        if all((x**2).is_Rational for x in pargs):        sqargs = [x**2 for x in pargs]        if all(sq.is_Rational and sq.is_positive for sq in sqargs):             r, b, a = split_surds(p)             res = a, b, r             return list(res)


Question: from sympy.combinatorics import Permutation         expr = _sympify(expr)         permutation = Permutation(permutation)        plist = permutation.args[0]        plist = permutation.array_form         if plist == sorted(plist):             return expr         obj = Basic.__new__(cls, expr, permutation)

Permutation args are now subtypes of Basic Permutation has currently a subtype in its args. I changed that to


Question: elif isinstance(expr, (MatrixSymbol, IndexedBase)):         return expr     elif isinstance(expr, CodegenArrayPermuteDims):        if expr.permutation.args[0] == [1, 0]:        if expr.permutation.array_form == [1, 0]:             return _RecognizeMatOp(Transpose, [_recognize_matrix_expression(expr.expr)])         elif isinstance(expr.expr, CodegenArrayTensorProduct):             ranks = expr.expr.subranksdiff --git a/sympy/combinatorics/perm_groups.py b/sympy/combinatorics/perm_groups.py-- a/sympy/combinatorics/perm_groups.py++ b/sympy/combinatorics/perm_groups.py


Question: >>> from sympy.combinatorics import Permutation, PermutationGroup         >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2))         >>> p.elements        {(3), (2 3), (3)(1 2), (1 2 3), (1 3 2), (1 3)}        {(1 2 3), (1 3 2), (1 3), (2 3), (3), (3)(1 2)}          """         return set(self._elements)diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py-- a/sympy/combinatorics/permutations.py++ b/sympy/combinatorics/permutations.py


Question: import random from collections import defaultdict from sympy.core import Basicfrom sympy.core.basic import Basic, Atom from sympy.core.compatibility import is_sequence, reduce, range, as_int from sympy.matrices import zeros from sympy.polys.polytools import lcm


Question: return Cycle(self)  class Permutation(Basic):class Permutation(Atom):     """     A permutation, alternatively known as an 'arrangement number' or 'ordering'     is an arrangement of the elements of an ordered list into a one-to-one


Question: Permutation([2, 1, 3, 0])          """        p = Basic.__new__(cls, perm)        p = super(Permutation, cls).__new__(cls)         p._array_form = perm         p._size = len(perm)         return pdiff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py-- a/sympy/printing/pycode.py++ b/sympy/printing/pycode.py


Question: return "%s(%s, %s)" % (             self._module_format("numpy.transpose"),             self._print(expr.expr),            self._print(expr.permutation.args[0]),            self._print(expr.permutation.array_form),         )      def _print_CodegenArrayElementwiseAdd(self, expr):diff --git a/sympy/printing/tensorflow.py b/sympy/printing/tensorflow.py-- a/sympy/printing/tensorflow.py++ b/sympy/printing/tensorflow.py


Question: return "%s(%s, %s)" % (             self._module_format("tensorflow.transpose"),             self._print(expr.expr),            self._print(expr.permutation.args[0]),            self._print(expr.permutation.array_form),         )      def _print_CodegenArrayElementwiseAdd(self, expr):


Question: # manipulate them like non-commutative scalars.                 return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)]) <ins>        if mat_class == MatAdd:            return mat_class(*matrices).doit(deep=False)</ins>         return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)     return _postprocessor

Exception when multiplying BlockMatrix containing ZeroMatrix blocks When a block matrix with zero blocks is defined then block-multiplying it once seems to work fine: but block-multiplying twice throws an exception: This seems to be caused by the fact that the zeros in are not but : However, I don't understand SymPy internals well enough to find out why this happens. I use Python 3.7.4 and sympy 1.4 (installed with pip).


Question: assumptions, kw_args = _filter_assumptions(kw_args)         if isinstance(label, string_types):            label = Symbol(label)            label = Symbol(label, **assumptions)         elif isinstance(label, Symbol):             assumptions = label._merge(assumptions)            label = Symbol(label.name)         elif isinstance(label, (MatrixBase, NDimArray)):             return label         elif isinstance(label, Iterable):

new of IndexedBase upcasts subclass of Symbol to Symbol First, thanks for creating SymPy. We're using it in a code generation framework: We noticed that our tests are failling when using the current master of SymPy. To reproduce run: While should work fine. The reason for this failure seems to be in the call of the constructor of . We're a calling it with a subclass of () which is essentially a sympy Symbol with type information. Is there a reason why the out-commented line is necessary? It causes our TypeSymbol to lose its type information by re-constructing a new Symbol. When I out-comment this line everything works fine again. In new of IndexedBase upcasts subclass of Symbol to Symbol First, thanks for creating SymPy. We're using it in a code generation framework: We noticed that our tests are failling when using the current master of SymPy. To reproduce run: While should work fine. The reason for this failure seems to be in the call of the constructor of . We're a calling it with a subclass of () which is essentially a sympy Symbol with type information. Is there a reason why the out-commented line is necessary? It causes our TypeSymbol to lose its type information by re-constructing a new Symbol. When I out-comment this line everything works fine again. In


Question: coords = [simplify(x*factor) for x in self.args]         return Point(coords, evaluate=False) <ins>    def __rmul__(self, factor):        """Multiply a factor by point's coordinates."""        return self.__mul__(factor)</ins>     def __neg__(self):         """Negate the point."""         coords = [-x for x in self.args]

Unexpected exception when multiplying geometry.Point and number This line works fine But when I write the same this way it raises an exception The expected behaviour is, that both lines give the same result


Question: return None  <ins>def refine_sign(expr, assumptions):    """    Handler for sign    Examples    ========    >>> from sympy.assumptions.refine import refine_sign    >>> from sympy import Symbol, Q, sign, im    >>> x = Symbol('x', real = True)    >>> expr = sign(x)    >>> refine_sign(expr, Q.positive(x) & Q.nonzero(x))    1    >>> refine_sign(expr, Q.negative(x) & Q.nonzero(x))    -1    >>> refine_sign(expr, Q.zero(x))    0    >>> y = Symbol('y', imaginary = True)    >>> expr = sign(y)    >>> refine_sign(expr, Q.positive(im(y)))    I    >>> refine_sign(expr, Q.negative(im(y)))    -I    """    arg = expr.args[0]    if ask(Q.zero(arg), assumptions):        return S.Zero    if ask(Q.real(arg)):        if ask(Q.positive(arg), assumptions):            return S.One        if ask(Q.negative(arg), assumptions):            return S.NegativeOne    if ask(Q.imaginary(arg)):        arg_re, arg_im = arg.as_real_imag()        if ask(Q.positive(arg_im), assumptions):            return S.ImaginaryUnit        if ask(Q.negative(arg_im), assumptions):            return -S.ImaginaryUnit    return expr</ins> handlers_dict = {     'Abs': refine_abs,     'Pow': refine_Pow,

Refine with sign Consider the following code: All the returned expression are . However, at least for and , the results should be . This probably is due to the lack of capabilities for . A PR similar to should fix this behaviour. Related issues: and .


Question: 'StrictGreaterThan': refine_Relational,     'StrictLessThan': refine_Relational,     're': refine_re,    'im': refine_im    'im': refine_im,    'sign': refine_sign }


Question: facs = factorint(r, limit=limit, use_trial=use_trial,                                      use_rho=use_rho, use_pm1=use_pm1,                                      verbose=verbose)                    factors.update(facs)                    for k, v in facs.items():                        factors[k] = factors.get(k, 0) + v                 raise StopIteration              # ...see if factorization can be terminated

sqrt(sympify('')) gives wrong answer It is easily verified that this answer is not correct; notably:


Question: else:             return self.func(arg) <ins>    def _eval_is_real(self):        arg = self.args[0]        if arg.is_real:            return True        # if `im` is of the form n*pi        # else, check if it is a number        re, im = arg.as_real_imag()        return (im%pi).is_zero</ins>     def _eval_is_extended_real(self):         if self.args[0].is_extended_real:             return True

Corrected functions in subclasses of Corrected the and functions. These functions are still sort of incomplete (couldn't think of all cases, any improvements are welcome). They can directly be used to define properties like and for , , and .


Question: def _eval_is_finite(self):         arg = self.args[0]        if arg.is_imaginary:            return True        return arg.is_finite      def _eval_is_zero(self):         arg = self.args[0]


Question: else:             return self.func(arg)     def _eval_is_real(self):        arg = self.args[0]        # `cosh(x)` is real for real OR purely imaginary `x`        if arg.is_real or arg.is_imaginary:            return True        # cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a)        # the imaginary part can be an expression like n*pi        # if not, check if the imaginary part is a number        re, im = arg.as_real_imag()        return (im%pi).is_zero     def _eval_is_positive(self):         if self.args[0].is_extended_real:             return True      def _eval_is_finite(self):         arg = self.args[0]        if arg.is_imaginary:            return True        return arg.is_finite   class tanh(HyperbolicFunction):


Question: else:             return self.func(arg) <ins>    def _eval_is_real(self):        from sympy import cos, sinh        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        # if denom = 0, tanh(arg) = zoo        if re == 0 and im % pi == pi/2:            return None        # check if im is of the form n*pi/2 to make sin(2*im) = 0        # if not, im could be a number, return False in that case        return (im % (pi/2)).is_zero</ins>     def _eval_is_extended_real(self):         if self.args[0].is_extended_real:             return True


Question: return self.args[0].is_negative      def _eval_is_finite(self):        from sympy import sinh, cos         arg = self.args[0]        re, im = arg.as_real_imag()        denom = cos(im)**2 + sinh(re)**2        if denom == 0:            return False        elif denom.is_number:            return True         if arg.is_extended_real:             return True


Question: from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.integers import floor <ins>from sympy import pi, Eqfrom sympy.logic import Or, Andfrom sympy.core.logic import fuzzy_or, fuzzy_and, fuzzy_bool</ins>  def _rewrite_hyperbolics_as_exp(expr):     expr = sympify(expr)

Modified ispositive for cosh function returns if x is real. Also modified the function to return the function itself or its negative if the function is positive or negative. Example: abs(cosh(x)) should simplify to cosh(x) for real x Sympy 1.0 only simplifies in a limited set of cases:


Question: sinh, tanh, acosh     """ <ins>    def _eval_is_positive(self):        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        im_mod = im % (2*pi)        if im_mod == 0:            return True        if re == 0:            if im_mod < pi/2 or im_mod > 3*pi/2:                return True            elif im_mod >= pi/2 or im_mod <= 3*pi/2:                return False        return fuzzy_or([fuzzy_and([fuzzy_bool(Eq(re, 0)),                         fuzzy_or([fuzzy_bool(im_mod < pi/2),                                   fuzzy_bool(im_mod > 3*pi/2)])]),                         fuzzy_bool(Eq(im_mod, 0))])    def _eval_is_nonnegative(self):        arg = self.args[0]        if arg.is_real:            return True        re, im = arg.as_real_imag()        im_mod = im % (2*pi)        if im_mod == 0:            return True        if re == 0:            if im_mod <= pi/2 or im_mod >= 3*pi/2:                return True            elif im_mod > pi/2 or im_mod < 3*pi/2:                return False        return fuzzy_or([fuzzy_and([fuzzy_bool(Eq(re, 0)),                         fuzzy_or([fuzzy_bool(im_mod <= pi/2), fuzzy_bool(im_mod >= 3*pi/2)])]),                         fuzzy_bool(Eq(im_mod, 0))])</ins>     def fdiff(self, argindex=1):         if argindex == 1:             return sinh(self.args[0])


Question: re, im = arg.as_real_imag()         return (im%pi).is_zero <del>    def _eval_is_positive(self):        if self.args[0].is_extended_real:            return True</del>     def _eval_is_finite(self):         arg = self.args[0]         return arg.is_finite


Question: return None     base_set = self.base_sets[0]     # Intersection between ImageSets with Integers as base set    # For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the    # diophantine equations f(n)=g(m).    # If the solutions for n are {h(t) : t in Integers} then we return    # {f(h(t)) : t in integers}.     if base_set is S.Integers:        g = None        gm = None         if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):            g = other.lamda.expr            gm = other.lamda.expr             m = other.lamda.variables[0]         elif other is S.Integers:            m = g = Dummy('x')        if g is not None:            f = self.lamda.expr            m = gm = Dummy('x')        if gm is not None:            fn = self.lamda.expr             n = self.lamda.variables[0]            # Diophantine sorts the solutions according to the alphabetic            # order of the variable names, since the result should not depend            # on the variable name, they are replaced by the dummy variables            # below            a, b = Dummy('a'), Dummy('b')            fa, ga = f.subs(n, a), g.subs(m, b)            solns = list(diophantine(fa - ga))            if not solns:            solns = list(diophantine(fn - gm, syms=(n, m)))            if len(solns) == 0:                 return EmptySet()            if len(solns) != 1:            elif len(solns) != 1:                 return            nsol = solns[0][0]  # since 'a' < 'b', nsol is first            t = nsol.free_symbols.pop()  # diophantine supplied symbol            nsol = nsol.subs(t, n)            if nsol != n:                # if nsol == n and we know were are working with                # a base_set of Integers then this was an unevaluated                # ImageSet representation of Integers, otherwise                # it is a new ImageSet intersection with a subset                # of integers                nsol = f.subs(n, nsol)            return imageset(Lambda(n, nsol), S.Integers)            else:                soln, solm = solns[0]                (t,) = soln.free_symbols                expr = fn.subs(n, soln.subs(t, n))                return imageset(Lambda(n, expr), S.Integers)      if other == S.Reals:         from sympy.solvers.solveset import solveset_real

Intersection of ImageSet gives incorrect answer. After git bisecting by this has changed the output of ping -


Question: elif issubclass(number_cls, Rational):             return (Rational(9, 10), S.One) <ins>    def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):        from sympy import Sum, Dummy        if (k_sym is not None) or (symbols is not None):            return self        k = Dummy('k', integer=True, nonnegative=True)        return Sum((-1)**k / (2*k+1)**2, (k, 0, S.Infinity))</ins>     def _sage_(self):         import sage.all as sage         return sage.catalan

Catalan rewrite and doctests for latex equations First, implement . Also, something I've been thinking about for while: we have lots of LaTeX in our docs. In many cases we could generate those equations ourselves instead of typing them manually (I found errors while doing for example). This PR should demonstrate the idea. what do you think? Will this work? Its certainly nice for maintainance, although it is probably slightly less readable... (If we want to do this widely, the latex printer could probably be optimized for things like and when it uses instead of .) <!-- BEGIN RELEASE NOTES --core Catalan can be rewritten as a sum <!-- END RELEASE NOTES --


Question: from __future__ import print_function, division from sympy.core import S, Basic, Add, Mul, symbolsfrom sympy.core import S, Basic, Add, Mul, symbols, Dummy from sympy.core.compatibility import range from sympy.functions.combinatorial.factorials import factorial from sympy.polys.polyerrors import (

interpolate could provide value instead of nan Since the default x value for interpolation is the interpolation at 5 could just return 115 instead of nan.


Question: @public def interpolate(data, x):     """    Construct an interpolating polynomial for the data points.    Construct an interpolating polynomial for the data points    evaluated at point x (which can be symbolic or numeric).      Examples     ========      >>> from sympy.polys.polyfuncs import interpolate    >>> from sympy.abc import x    >>> from sympy.abc import a, b, x      A list is interpreted as though it were paired with a range starting     from 1:


Question: >>> interpolate({-1: 2, 1: 2, 2: 5}, x)     x**2 + 1     If the interpolation is going to be used only once then the    value of interest can be passed instead of passing a symbol:    >>> interpolate([1, 4, 9], 5)    25    Symbolic coordinates are also supported:    >>> [(i,interpolate((a, b), i)) for i in range(1, 4)]    [(1, a), (2, b), (3, -a + 2*b)]     """     n = len(data)    poly = None      if isinstance(data, dict):        if x in data:            return S(data[x])         X, Y = list(zip(*data.items()))        poly = interpolating_poly(n, x, X, Y)     else:         if isinstance(data[0], tuple):             X, Y = list(zip(*data))            poly = interpolating_poly(n, x, X, Y)            if x in X:                return S(Y[X.index(x)])         else:            if x in range(1, n + 1):                return S(data[x - 1])             Y = list(data)            X = list(range(1, n + 1))             numert = Mul(*[(x - i) for i in range(1, n + 1)])            denom = -factorial(n - 1) if n%2 == 0 else factorial(n - 1)            coeffs = []            for i in range(1, n + 1):                coeffs.append(numert/(x - i)/denom)                denom = denom/(i - n)*i            poly = Add(*[coeff*y for coeff, y in zip(coeffs, Y)])    return poly.expand()    try:        return interpolating_poly(n, x, X, Y).expand()    except ValueError:        d = Dummy()        return interpolating_poly(n, d, X, Y).expand().subs(d, x)   @publicdiff --git a/sympy/polys/specialpolys.py b/sympy/polys/specialpolys.py-- a/sympy/polys/specialpolys.py++ b/sympy/polys/specialpolys.py


Question: from sympy.core import Add, Mul, Symbol, sympify, Dummy, symbols from sympy.core.compatibility import range, string_types<ins>from sympy.core.containers import Tuple</ins> from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.ntheory import nextprime


Question: from sympy.polys.polyclasses import DMP from sympy.polys.polytools import Poly, PurePoly from sympy.polys.polyutils import _analyze_gensfrom sympy.utilities import subsets, publicfrom sympy.utilities import subsets, public, filldedent   @public


Question: @public def interpolating_poly(n, x, X='x', Y='y'):    """Construct Lagrange interpolating polynomial for ``n`` data points. """    """Construct Lagrange interpolating polynomial for ``n``    data points. If a sequence of values are given for ``X`` and ``Y``    then the first ``n`` values will be used.    """    ok = getattr(x, 'free_symbols', None)     if isinstance(X, string_types):         X = symbols("%s:%s" % (X, n))    elif ok and ok & Tuple(*X).free_symbols:        ok = False      if isinstance(Y, string_types):         Y = symbols("%s:%s" % (Y, n))    elif ok and ok & Tuple(*Y).free_symbols:        ok = False    if not ok:        raise ValueError(filldedent('''            Expecting symbol for x that does not appear in X or Y.            Use `interpolate(list(zip(X, Y)), x)` instead.'''))      coeffs = []    numert = Mul(*[(x - u) for u in X])    numert = Mul(*[x - X[i] for i in range(n)])      for i in range(n):         numer = numert/(x - X[i])


Question: def __eq__(self, other):         try:            other = sympify(other)            other = _sympify(other)             if not isinstance(other, Expr):                 return False         except (SympifyError, SyntaxError):

Sympy incorrectly attempts to eval reprs in its eq method Passing strings produced by unknown objects into eval is very bad. It is especially surprising for an equality check to trigger that kind of behavior. This should be fixed ASAP. Repro code: Results in: On the line: Where code is: Full trace: Related issue: an unknown object whose repr is will incorrectly compare as equal to a sympy symbol x:


Question: from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet,                         EmptySet, Intersection, Range) from sympy.sets.fancysets import Integers, Naturals, Reals<ins>from sympy.functions.elementary.exponential import match_real_imag</ins>   _x, _y = symbols("x y")

imageset broken for complex numbers With current master: The (or any other value) is simply dropped.


Question: match = expr.match(a*n + b)     if match and match[a]:         # canonical shift        b = match[b]        if abs(match[a]) == 1:        a, b = match[a], match[b]        if a in [1, -1]:            # drop integer addends in b             nonint = []             for bi in Add.make_args(b):                 if not bi.is_integer:                     nonint.append(bi)             b = Add(*nonint)        if b.is_number and match[a].is_real:            mod = b % match[a]            reps = dict([(m, m.args[0]) for m in mod.atoms(Mod)                if not m.args[0].is_real])            mod = mod.xreplace(reps)            expr = match[a]*n + mod        else:            expr = match[a]*n + b        if b.is_number and a.is_real:            # avoid Mod for complex numbers, #11391            br, bi = match_real_imag(b)            if br and br.is_comparable and a.is_comparable:                br %= a                b = br + S.ImaginaryUnit*bi        elif b.is_number and a.is_imaginary:            br, bi = match_real_imag(b)            ai = a/S.ImaginaryUnit            if bi and bi.is_comparable and ai.is_comparable:                bi %= ai                b = br + S.ImaginaryUnit*bi        expr = a*n + b      if expr != f.expr:         return ImageSet(Lambda(n, expr), S.Integers)


Question: for f in list(factors.keys()):                 if isinstance(f, Rational) and not isinstance(f, Integer):                     p, q = Integer(f.p), Integer(f.q)                    factors[p] = (factors[p] if p in factors else 0) + factors[f]                    factors[q] = (factors[q] if q in factors else 0) - factors[f]                    factors[p] = (factors[p] if p in factors else S.Zero) + factors[f]                    factors[q] = (factors[q] if q in factors else S.Zero) - factors[f]                     factors.pop(f)             if i:                 factors[I] = S.One*i

Simplify of simple trig expression fails trigsimp in various versions, including 1.5, incorrectly simplifies cos(x)+sqrt(sin(x)**2) as though it were cos(x)+sin(x) for general complex x. (Oddly it gets this right if x is real.) Embarrassingly I found this by accident while writing sympy-based teaching material...


Question: args = []         for factor, exp in self.factors.items():             if exp != 1:                b, e = factor.as_base_exp()                if isinstance(exp, int):                    e = _keep_coeff(Integer(exp), e)                elif isinstance(exp, Rational):                if isinstance(exp, Integer):                    b, e = factor.as_base_exp()                     e = _keep_coeff(exp, e)                    args.append(b**e)                 else:                    e *= exp                args.append(b**e)                    args.append(factor**exp)             else:                 args.append(factor)         return Mul(*args)


Question: @_sympifyit('other', NotImplemented)     def __add__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.NegativeInfinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__add__(self, other)     __radd__ = __add__      @_sympifyit('other', NotImplemented)     def __sub__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__sub__(self, other)      @_sympifyit('other', NotImplemented)     def __rsub__(self, other):

Why pretty print of "oo - oo" has result "nan", if the evaluation is disabled?


Question: @_sympifyit('other', NotImplemented)     def __mul__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other.is_zero or other is S.NaN:                 return S.NaN             if other.is_extended_positive:                 return self             return S.NegativeInfinity        return NotImplemented        return Number.__mul__(self, other)     __rmul__ = __mul__      @_sympifyit('other', NotImplemented)     def __div__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or \                 other is S.NegativeInfinity or \                     other is S.NaN:


Question: if other.is_extended_nonnegative:                 return self             return S.NegativeInfinity        return NotImplemented        return Number.__div__(self, other)      __truediv__ = __div__


Question: @_sympifyit('other', NotImplemented)     def __add__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__add__(self, other)     __radd__ = __add__      @_sympifyit('other', NotImplemented)     def __sub__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.NegativeInfinity or other is S.NaN:                 return S.NaN             return self        return NotImplemented        return Number.__sub__(self, other)      @_sympifyit('other', NotImplemented)     def __rsub__(self, other):


Question: @_sympifyit('other', NotImplemented)     def __mul__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other.is_zero or other is S.NaN:                 return S.NaN             if other.is_extended_positive:                 return self             return S.Infinity        return NotImplemented        return Number.__mul__(self, other)     __rmul__ = __mul__      @_sympifyit('other', NotImplemented)     def __div__(self, other):        if isinstance(other, Number):        if isinstance(other, Number) and global_evaluate[0]:             if other is S.Infinity or \                 other is S.NegativeInfinity or \                     other is S.NaN:


Question: if other.is_extended_nonnegative:                 return self             return S.Infinity        return NotImplemented        return Number.__div__(self, other)      __truediv__ = __div__


Question: for z0 in range(0, abs(_c)):                     # Check if the coefficients of y and x obtained are integers or not                     if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and                            divisible(e*sqc**g*z0**2 + E*z0 + e*sqc*F, _c)):                            divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)):                         sol.add((solve_x(z0), solve_y(z0)))      # (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper

ImageSet of n**2-1 returns EmptySet as intersection with Integers (diophantine bug)


Question: ref = self.start         elif self.stop.is_finite:             ref = self.stop        else:            return other.is_Integer        if (ref - other) % self.step:  # off sequence        else:  # both infinite; step is +/- 1 (enforced by __new__)            return S.true        if self.size == 1:            return Eq(other, self[0])        res = (ref - other) % self.step        if res == S.Zero:            return And(other >= self.inf, other <= self.sup)        elif res.is_Integer:  # off sequence             return S.false        return _sympify(other >= self.inf and other <= self.sup)        else:  # symbolic/unsimplified residue modulo step            return None      def __iter__(self):         if self.has(Symbol):

Range(1).intersect(FiniteSet(n)) raises TypeError: cannot determine truth value of Relational


Question: def as_relational(self, x):         """Rewrite a Range in terms of equalities and logic operators. """         from sympy.functions.elementary.integers import floor        return And(            Eq(x, floor(x)),            x >= self.inf if self.inf in self else x > self.inf,            x <= self.sup if self.sup in self else x < self.sup)        if self.size == 1:            return Eq(x, self[0])        else:            return And(                Eq(x, floor(x)),                x >= self.inf if self.inf in self else x > self.inf,                x <= self.sup if self.sup in self else x < self.sup)   # Using range from compatibility above (xrange on Py2)diff --git a/sympy/sets/handlers/issubset.py b/sympy/sets/handlers/issubset.py-- a/sympy/sets/handlers/issubset.py++ b/sympy/sets/handlers/issubset.py


Question: from sympy import Sfrom sympy import S, Symbol from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or from sympy.core.relational import Eq from sympy.sets.sets import FiniteSet, Interval, Set, Union


Question: cond_right = a_range.sup <= b_interval.right         return fuzzy_and([cond_left, cond_right]) @dispatch(Range, FiniteSet)def is_subset_sets(a_range, b_finiteset): # noqa:F811    try:        a_size = a_range.size    except ValueError:        # symbolic Range of unknown size        return None    if a_size > len(b_finiteset):        return False    elif any(arg.has(Symbol) for arg in a_range.args):        return fuzzy_and(b_finiteset.contains(x) for x in a_range)    else:        # Checking A \ B == EmptySet is more efficient than repeated naive        # membership checks on an arbitrary FiniteSet.        a_set = set(a_range)        b_remaining = len(b_finiteset)        # Symbolic expressions and numbers of unknown type (integer or not) are        # all counted as "candidates", i.e. *potentially* matching some a in        # a_range.        cnt_candidate = 0        for b in b_finiteset:            if b.is_Integer:                a_set.discard(b)            elif fuzzy_not(b.is_integer):                pass            else:                cnt_candidate += 1            b_remaining -= 1            if len(a_set) > b_remaining + cnt_candidate:                return False            if len(a_set) == 0:                return True        return None @dispatch(Interval, Range) def is_subset_sets(a_interval, b_range): # noqa:F811     if a_interval.measure.is_extended_nonzero:diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


Question: else:             args = list(map(sympify, args))         args = list(ordered(set(args), Set._infimum_key))        _args_set = set(args)        args = list(ordered(_args_set, Set._infimum_key))         obj = Basic.__new__(cls, *args)        obj._args_set = _args_set         return obj      def _eval_Eq(self, other):


Question: """         Tests whether an element, other, is in the set.         Relies on Python's set class. This tests for object equality        All inputs are sympified        The actual test is for mathematical equality (as opposed to        syntactical equality). In the worst case all elements of the        set must be checked.          Examples         ========


Question: False          """        # evaluate=True is needed to override evaluate=False context;        # we need Eq to do the evaluation        return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True)) for e in self.args)        if other in self._args_set:            return True        else:            # evaluate=True is needed to override evaluate=False context;            # we need Eq to do the evaluation            return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True))                for e in self.args)      def _eval_is_subset(self, other):         return fuzzy_and(other._contains(e) for e in self.args)


Question: @property     def _boundary(self):        return self        return S.Reals   class Naturals(with_metaclass(Singleton, Set)):diff --git a/sympy/sets/handlers/union.py b/sympy/sets/handlers/union.py-- a/sympy/sets/handlers/union.py++ b/sympy/sets/handlers/union.py

Are of 's properties valid? currently, there properties aren't initialized . if there properties are thought wheather Q(S.Rationals) is open or closed set in R (S.Reals), should return and . if use there properties as undefined, should return a exception ? Are of 's properties valid? currently, there properties aren't initialized . if there properties are thought wheather Q(S.Rationals) is open or closed set in R (S.Reals), should return and . if use there properties as undefined, should return a exception ?


Question: from sympy import (Interval, Intersection, Set, EmptySet, S, sympify,                    FiniteSet, Union, ComplexRegion, ProductSet) from sympy.multipledispatch import dispatchfrom sympy.sets.fancysets import Integersfrom sympy.sets.fancysets import (Naturals, Naturals0, Integers, Rationals,                                  Reals) from sympy.sets.sets import UniversalSet  @dispatch(Naturals0, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Rationals, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Rationals, Naturals0)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Naturals0)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Rationals)def union_sets(a, b): # noqa:F811    return a @dispatch(Integers, Set) def union_sets(a, b): # noqa:F811     intersect = Intersection(a, b)diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


Question: def is_open(self):         """         Property method to check whether a set is open.         A set is open if and only if it has an empty intersection with its        boundary.        boundary. In particular, a subset A of the reals is open if and only        if each one of its points is contained in an open interval that is a        subset of A.          Examples         ========         >>> from sympy import S         >>> S.Reals.is_open         True        >>> S.Rationals.is_open        False         """        if not Intersection(self, self.boundary):            return True        # We can't confidently claim that an intersection exists        return None        return Intersection(self, self.boundary).is_empty      @property     def is_closed(self):         """        A property method to check whether a set is closed. A set is closed        if its complement is an open set.        A property method to check whether a set is closed.        A set is closed if its complement is an open set. The closedness of a        subset of the reals is determined with respect to R and its standard        topology.          Examples         ========


Question: if syms != var:                 dict_sym_index = dict(zip(syms, range(len(syms))))                 return {tuple([t[dict_sym_index[i]] for i in var])                            for t in diophantine(eq, param)}                            for t in diophantine(eq, param, permute=permute)}         n, d = eq.as_numer_denom()         if n.is_number:             return set()

diophantine: incomplete results depending on syms order with permute=True diophantine: incomplete results depending on syms order with permute=True


Question: if _half(other):                         if b.is_negative is True:                             return S.NegativeOne**other*Pow(-b, e*other)                        if b.is_extended_real is False:                            return Pow(b.conjugate()/Abs(b)**2, other)                        elif b.is_negative is False:                            return Pow(b, -other)                 elif e.is_even:                     if b.is_extended_real:                         b = abs(b)

Recursion error: sqrt(1 / tan(1 + I)) There should be an additional check on this line:


Question: from sympy.core.compatibility import as_int, range from sympy.core.function import Function<ins>from sympy.utilities.iterables import cartes</ins> from sympy.core.numbers import igcd, igcdex, mod_inverse from sympy.core.power import isqrt from sympy.core.singleton import S

nthrootmod function misses one root of x = 0 mod p. When in the equation x*n = a mod p , when a % p == 0. Then x = 0 mod p is also a root of this equation. But right now does not check for this condition. has a root . But it does not return it.


Question: return res     return min(res) <ins>def _nthroot_mod_composite(a, n, m):    """    Find the solutions to ``x**n = a mod m`` when m is not prime.    """    from sympy.ntheory.modular import crt    f = factorint(m)    dd = {}    for p, e in f.items():        tot_roots = set()        if e == 1:            tot_roots.update(nthroot_mod(a, n, p, True) or [])        else:            for root in nthroot_mod(a, n, p, True) or []:                rootn = pow(root, n)                diff = (rootn // (root or 1) * n) % p                if diff != 0:                    ppow = p                    for j in range(1, e):                        ppow *= p                        root = (root - (rootn - a) * mod_inverse(diff, p)) % ppow                    tot_roots.add(root)                else:                    new_base = p                    roots_in_base = {root}                    while new_base < pow(p, e):                        new_base *= p                        new_roots = set()                        for k in roots_in_base:                            if (pow(k, n) - a) % (new_base) != 0:                                continue                            while k not in new_roots:                                new_roots.add(k)                                k = (k + (new_base // p)) % new_base                        roots_in_base = new_roots                    tot_roots = tot_roots | roots_in_base        dd[pow(p, e)] = tot_roots    a = []    m = []    for x, y in dd.items():        m.append(x)        a.append(list(y))    return sorted(set(crt(m, list(i))[0] for i in cartes(*a)))</ins>  def nthroot_mod(a, n, p, all_roots=False):     """


Question: if n == 2:         return sqrt_mod(a, p, all_roots)     # see Hackman "Elementary Number Theory" (2009), page 76    if not isprime(p):        return _nthroot_mod_composite(a, n, p)    if a % p == 0:        return [0]     if not is_nthpow_residue(a, n, p):         return None    if not isprime(p):        raise NotImplementedError("Not implemented for composite p")     if (p - 1) % n == 0:         return _nthroot_mod1(a, n, p, all_roots)     # The roots of ``x**n - a = 0 (mod p)`` are roots of


Question: # diophantine equations f(n)=g(m).     # If the solutions for n are {h(t) : t in Integers} then we return     # {f(h(t)) : t in integers}.    # If the solutions for n are {n_1, n_2, ..., n_k} then we return    # {f(n_i) : 1 <= i <= k}.     if base_set is S.Integers:         gm = None         if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):             gm = other.lamda.expr            m = other.lamda.variables[0]            var = other.lamda.variables[0]            # Symbol of second ImageSet lambda must be distinct from first            m = Dummy('m')            gm = gm.subs(var, m)         elif other is S.Integers:            m = gm = Dummy('x')            m = gm = Dummy('m')         if gm is not None:             fn = self.lamda.expr             n = self.lamda.variables[0]            solns = list(diophantine(fn - gm, syms=(n, m)))            try:                solns = list(diophantine(fn - gm, syms=(n, m), permute=True))            except (TypeError, NotImplementedError):                # TypeError if equation not polynomial with rational coeff.                # NotImplementedError if correct format but no solver.                return            # 3 cases are possible for solns:            # - empty set,            # - one or more parametric (infinite) solutions,            # - a finite number of (non-parametric) solution couples.            # Among those, there is one type of solution set that is            # not helpful here: multiple parametric solutions.             if len(solns) == 0:                 return EmptySet            elif len(solns) != 1:                return            elif any(not isinstance(s, int) and s.free_symbols                     for tupl in solns for s in tupl):                if len(solns) == 1:                    soln, solm = solns[0]                    (t,) = soln.free_symbols                    expr = fn.subs(n, soln.subs(t, n)).expand()                    return imageset(Lambda(n, expr), S.Integers)                else:                    return             else:                soln, solm = solns[0]                (t,) = soln.free_symbols                expr = fn.subs(n, soln.subs(t, n))                return imageset(Lambda(n, expr), S.Integers)                return FiniteSet(*(fn.subs(n, s[0]) for s in solns))      if other == S.Reals:         from sympy.solvers.solveset import solveset_realdiff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py-- a/sympy/solvers/diophantine.py++ b/sympy/solvers/diophantine.py

ImageSet(Lambda(n, n**2), S.Integers).intersect(S.Integers) raises AttributeError This is in the related intersection code. See also: , and


Question: else:             raise TypeError     except (TypeError, NotImplementedError):        terms = factor_list(eq)[1]        fl = factor_list(eq)        if fl[0].is_Rational and fl[0] != 1:            return diophantine(eq/fl[0], param=param, syms=syms, permute=permute)        terms = fl[1]      sols = set([])


Question: def _eval_as_set(self):         # self is univariate and periodicity(self, x) in (0, None)         from sympy.solvers.inequalities import solve_univariate_inequality        from sympy.sets.conditionset import ConditionSet         syms = self.free_symbols         assert len(syms) == 1         x = syms.pop()        return solve_univariate_inequality(self, x, relational=False)        try:            xset = solve_univariate_inequality(self, x, relational=False)        except NotImplementedError:            # solve_univariate_inequality raises NotImplementedError for            # unsolvable equations/inequalities.            xset = ConditionSet(x, self, S.Reals)        return xset      @property     def binary_symbols(self):

raises instead of returning The problem is Here raises but probably a should be returned by instead. The obvious result of here is Originally posted by in


Question: "gothic_re_im": False,         "decimal_separator": "period",         "perm_cyclic": True,<ins>        "parenthesize_super": True,</ins>         "min": None,         "max": None,     }  # type: Dict[str, Any]

Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /


Question: def parenthesize_super(self, s):         """ Parenthesize s if there is a superscript in s"""        if "^" in s:        if "^" in s and self._settings['parenthesize_super']:             return r"\left({}\right)".format(s)        elif "^" in s and not self._settings['parenthesize_super']:            return self.embed_super(s)         return s      def embed_super(self, s):


Question: p, q = expr.exp.p, expr.exp.q             # issue #12886: add parentheses for superscripts raised to powers             if '^' in base and expr.base.is_Symbol:                base = r"\left(%s\right)" % base                base = self.parenthesize_super(base)             if expr.base.is_Function:                 return self._print(expr.base, exp="%s/%s" % (p, q))             return r"%s^{%s/%s}" % (base, p, q)


Question: # to powers         base = self.parenthesize(expr.base, PRECEDENCE['Pow'])         if '^' in base and expr.base.is_Symbol:            base = r"\left(%s\right)" % base            base = self.parenthesize_super(base)         elif (isinstance(expr.base, Derivative)             and base.startswith(r'\left(')             and re.match(r'\\left\(\\d?d?dot', base)


Question: else:                     name = r"\operatorname{%s}^{-1}" % func             elif exp is not None:                name = r'%s^{%s}' % (self._hprint_Function(func), exp)                func_tex = self._hprint_Function(func)                func_tex = self.parenthesize_super(func_tex)                name = r'%s^{%s}' % (func_tex, exp)             else:                 name = self._hprint_Function(func)


Question: mat_delim="[", mat_str=None, mode="plain", mul_symbol=None,           order=None, symbol_names=None, root_notation=True,           mat_symbol_style="plain", imaginary_unit="i", gothic_re_im=False,          decimal_separator="period", perm_cyclic=True):          decimal_separator="period", perm_cyclic=True, parenthesize_super=True):     r"""Convert the given expression to LaTeX string representation.      Parameters


Question: when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon         separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when         ``comma`` is chosen and [1,2,3] for when ``period`` is chosen.<ins>    parenthesize_super : boolean, optional        If set to ``False``, superscripted expressions will not be parenthesized when        powered. Default is ``True``, which parenthesizes the expression when powered.</ins>     min: Integer or None, optional         Sets the lower bound for the exponent to print floating point numbers in         fixed-point format.


Question: 'gothic_re_im': gothic_re_im,         'decimal_separator': decimal_separator,         'perm_cyclic' : perm_cyclic,<ins>        'parenthesize_super' : parenthesize_super,</ins>         'min': min,         'max': max,     }


Question: self._print(expr.matrix),                                self._print(expr.vector)) <ins>    def _print_ZeroMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.zeros'),            self._print(expr.shape))    def _print_OneMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.ones'),            self._print(expr.shape))    def _print_FunctionMatrix(self, expr):        from sympy.core.function import Lambda        from sympy.abc import i, j        lamda = expr.lamda        if not isinstance(lamda, Lambda):            lamda = Lambda((i, j), lamda(i, j))        return '{}(lambda {}: {}, {})'.format(self._module_format('numpy.fromfunction'),            ', '.join(self._print(arg) for arg in lamda.args[0]),            self._print(lamda.args[1]), self._print(expr.shape))    def _print_HadamardProduct(self, expr):        func = self._module_format('numpy.multiply')        return ''.join('{}({}, '.format(func, self._print(arg)) \            for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),            ')' * (len(expr.args) - 1))    def _print_KroneckerProduct(self, expr):        func = self._module_format('numpy.kron')        return ''.join('{}({}, '.format(func, self._print(arg)) \            for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),            ')' * (len(expr.args) - 1))    def _print_Adjoint(self, expr):        return '{}({}({}))'.format(            self._module_format('numpy.conjugate'),            self._module_format('numpy.transpose'),            self._print(expr.args[0]))    def _print_DiagonalOf(self, expr):        vect = '{}({})'.format(            self._module_format('numpy.diag'),            self._print(expr.arg))        return '{}({}, (-1, 1))'.format(            self._module_format('numpy.reshape'), vect)    def _print_DiagMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.diagflat'),            self._print(expr.args[0]))    def _print_DiagonalMatrix(self, expr):        return '{}({}, {}({}, {}))'.format(self._module_format('numpy.multiply'),            self._print(expr.arg), self._module_format('numpy.eye'),            self._print(expr.shape[0]), self._print(expr.shape[1]))</ins>     def _print_Piecewise(self, expr):         "Piecewise function printer"         exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args))

[WIP] Additional matrix support for NumPy printer <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. ". See . Please also write a comment on that issue linking back to this pull request once it is open. -- Adds support for the following matrix expressions to the NumPy printer: [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] <!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --printing numpy printer support for more matrix expressions <!-- END RELEASE NOTES --


Question: if types:             types = tuple(                 [t if isinstance(t, type) else type(t) for t in types])        nodes = preorder_traversal(self)        if types:            result = {node for node in nodes if isinstance(node, types)}         else:            types = (Atom,)        result = set()        for expr in preorder_traversal(self):            if isinstance(expr, types):                result.add(expr)            result = {node for node in nodes if not node.args}         return result      @property

() should return objects with no args instead of subclasses of Atom with no arguments returns subclasses of in . But the correct definition of a leaf node should be that it has no . This should be easy to fix, but one needs to check that this doesn't affect the performance.


Question: if isinstance(a, Cycle):  # f                 return cls._af_new(a.list(size))             if not is_sequence(a):  # b<ins>                if size is not None and a + 1 > size:                    raise ValueError('size is too small when max is %s' % a)</ins>                 return cls._af_new(list(range(a + 1)))             if has_variety(is_sequence(ai) for ai in a):                 ok = False

combinatorics.Permutation - exception not raised if wrong size is passed to constructor If I create object from list, which length is greater than argument, then the argument is ignored (and exception is not raised): Is there any reason for such behaviour? It seems to me that it would be better to raise an exception.


Question: raise ValueError('there were repeated elements.')         temp = set(temp)         if not is_cycle and \                any(i not in temp for i in range(len(temp))):            raise ValueError("Integers 0 through %s must be present." %                             max(temp))        if not is_cycle:            if any(i not in temp for i in range(len(temp))):                raise ValueError('Integers 0 through %s must be present.' %                max(temp))            if size is not None and temp and max(temp) + 1 > size:                raise ValueError('max element should not exceed %s' % (size - 1))          if is_cycle:             # it's not necessarily canonical so we won't storediff --git a/sympy/matrices/common.py b/sympy/matrices/common.py-- a/sympy/matrices/common.py++ b/sympy/matrices/common.py


Question: isinstance(perm[0], Iterable):             if direction == 'forward':                 perm = list(reversed(perm))            perm = Permutation(perm, size=max_index)            perm = Permutation(perm, size=max_index+1)         else:            perm = Permutation(perm, size=max_index)            perm = Permutation(perm, size=max_index+1)          if orientation == 'rows':             return self._eval_permute_rows(perm)


Question: from sympy.core.symbol import _filter_assumptions, Symbol from sympy.core.compatibility import (is_sequence, NotIterable,                                       Iterable)from sympy.core.logic import fuzzy_boolfrom sympy.core.logic import fuzzy_bool, fuzzy_not from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta

Idx object can accepts non-integer bounds It is my understanding that this code should not work: the lower and upper bounds should be integers. Instead it runs without any errors: Note however that: produces the expected result: The check for integer dimension should be done to both upper and lower bounds when a tuple is given as argument.


Question: raise TypeError("Idx object requires integer bounds.")             args = label, Tuple(*range)         elif isinstance(range, Expr):            if not (range.is_integer or range is S.Infinity):            if range is not S.Infinity and fuzzy_not(range.is_integer):                 raise TypeError("Idx object requires an integer dimension.")             args = label, Tuple(0, range - 1)         elif range:


Question: data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)                         for j in range(len(mats))]                         for i in range(len(mats))]        return ImmutableDenseMatrix(data)        return ImmutableDenseMatrix(data, evaluate=False)      @property     def shape(self):

BlockDiagMatrix with one element cannot be converted to regular Matrix Creating a BlockDiagMatrix with one Matrix element will raise if trying to convert it back to a regular Matrix: Instead having two elements will work as expected: This issue exists for sympy 1.5.1 but not for sympy 1.4


Question: return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)),                          self.convergence_statement), (self, True)) <ins>    def _eval_nseries(self, x, n, logx):        from sympy.functions import factorial, RisingFactorial        from sympy import Order, Add        arg = self.args[2]        x0 = arg.limit(x, 0)        ap = self.args[0]        bq = self.args[1]        if x0 != 0:            return super(hyper, self)._eval_nseries(x, n, logx)        terms = []        for i in range(n):            num = 1            den = 1            for a in ap:                num *= RisingFactorial(a, i)            for b in bq:                den *= RisingFactorial(b, i)            terms.append(((num/den) * (arg**i)) / factorial(i))        return (Add(*terms) + Order(x**n,x))</ins>     @property     def argument(self):         """ Argument of the hypergeometric function. """

AttributeError: integrate(1 / (1 + x4)(S(1)/4), [x, 0, oo]) It is trying to compute the of a hypergeometric function:


Question: expr = expr.expr          args, indices, free, dum = cls._contract_indices_for_derivative(            expr, variables)            S(expr), variables)          obj = TensExpr.__new__(cls, *args)

Random test failing in testtensorpartial_deriv It happened in I suspect the problem is the random value sometimes get zero and doesn't evaluate.


Question: result = obj         if isinstance(obj.expr, TensAdd):        if not args[0].free_symbols:            return S.Zero        elif isinstance(obj.expr, TensAdd):             # take care of sums of multi PDs             result = obj.expr.func(*[                     self.func(a, *obj.variables)._expand_partial_derivative()


Question: rv = S.One         if cargs:<ins>            if e.is_Rational:                npow, cargs = sift(cargs, lambda x: x.is_Pow and                    x.exp.is_Rational and x.base.is_number,                    binary=True)                rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])</ins>             rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])         if other:             rv *= self.func(Mul(*other), e, evaluate=False)

sqrt(8)**Rational(2, 3) doesn't simplify The results should just be .


Question: <ins>"""The Schur number S(k) is the largest integer n for which the interval [1,n]can be partitioned into k sum-free sets.(http://mathworld.wolfram.com/SchurNumber.html)"""import mathfrom sympy.core import Sfrom sympy.core.basic import Basicfrom sympy.core.function import Functionfrom sympy.core.numbers import Integerclass SchurNumber(Function):    """    This function creates a SchurNumber object    which is evaluated for k <= 4 otherwise only    the lower bound information can be retrieved.    Examples    ========    >>> from sympy.combinatorics.schur_number import SchurNumber    Since S(3) = 13, hence the output is a number    >>> SchurNumber(3)    13    We don't know the schur number for values greater than 4, hence    only the object is returned    >>> SchurNumber(6)    SchurNumber(6)    Now, the lower bound information can be retrieved using lower_bound()    method    >>> SchurNumber(6).lower_bound()    364    """    @classmethod    def eval(cls, k):        if k.is_Number:            if k is S.Infinity:                return S.Infinity            if k.is_zero:                return 0            if not k.is_integer or k.is_negative:                raise ValueError("k should be a positive integer")            first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44}            if k <= 4:                return Integer(first_known_schur_numbers[k])    def lower_bound(self):        f_ = self.args[0]        return (3**f_ - 1)/2def _schur_subsets_number(n):    if n is S.Infinity:        raise ValueError("Input must be finite")    if n <= 0:        raise ValueError("n must be a non-zero positive integer.")    elif n <= 3:        min_k = 1    else:        min_k = math.ceil(math.log(2*n + 1, 3))    return Integer(min_k)def schur_partition(n):    """    This function returns the partition in the minimum number of sum-free subsets    according to the lower bound given by the Schur Number.    Parameters    ==========    n: a number        n is the upper limit of the range [1, n] for which we need to find and        return the minimum number of free subsets according to the lower bound        of schur number    Returns    =======    List of lists        List of the minimum number of sum-free subsets    Notes    =====    It is possible for some n to make the partition into less    subsets since the only known Schur numbers are:    S(1) = 1, S(2) = 4 , S(3) = 13, S(4) = 44.    e.g for n = 44 the lower bound from the function above is 5 subsets but it has been proven    that can be done with 4 subsets.    Examples    ========    For n = 1, 2, 3 the answer is the set itself    >>> from sympy.combinatorics.schur_number import schur_partition    >>> schur_partition(2)    [[1, 2]]    For n > 3, the answer is the minimum number of sum-free subsets:    >>> schur_partition(5)    [[3, 2], [5], [1, 4]]    >>> schur_partition(8)    [[3, 2], [6, 5, 8], [1, 4, 7]]    """    if isinstance(n, Basic) and not n.is_Number:        raise ValueError("Input value must be a number")    number_of_subsets = _schur_subsets_number(n)    if n == 1:        sum_free_subsets = [[1]]    elif n == 2:        sum_free_subsets = [[1, 2]]    elif n == 3:        sum_free_subsets = [[1, 2, 3]]    else:        sum_free_subsets = [[1, 4], [2, 3]]    while len(sum_free_subsets) < number_of_subsets:        sum_free_subsets = _generate_next_list(sum_free_subsets, n)        missed_elements = [3*k + 1 for k in range(len(sum_free_subsets), (n-1)//3 + 1)]        sum_free_subsets[-1] += missed_elements    return sum_free_subsetsdef _generate_next_list(current_list, n):    new_list = []    for item in current_list:        temp_1 = [number*3 for number in item if number*3 <= n]        temp_2 = [number*3 - 1 for number in item if number*3 - 1 <= n]        new_item = temp_1 + temp_2        new_list.append(new_item)    last_list = [3*k + 1 for k in range(0, len(current_list)+1) if 3*k + 1 <= n]    new_list.append(last_list)    current_list = new_list    return current_list</ins>

Added new feature SchurNumber <!-- I have a new feature in the combinatorics module the Schurnumber --The Schur number S(k) is the largest integer n for which the interval [1,n] can be partitioned into k sum-free sets. I have also made the partition which can be proven by induction and I have test cases


Question: from __future__ import print_function, division from functools import wrapsfrom functools import wraps, reducefrom operator import mul  from sympy.core import (     S, Basic, Expr, I, Integer, Add, Mul, Dummy, Tuple

sqf and sqflist output is not consistant The example below is wrong in the sense that we should have (x*2 - 5_x + 6, 3) and not 2 factors of multiplicity 3. whereas below is correct --- one factor of multiplicity 2


Question: if arg.is_Number:             coeff *= arg             continue        if arg.is_Mul:            args.extend(arg.args)            continue        if arg.is_Pow:        elif arg.is_Pow:             base, exp = arg.args             if base.is_Number and exp.is_Number:                 coeff *= arg


Question: other.append((f, k))                  factors.append((_factors_product(other), exp))<ins>    if method == 'sqf':        factors = [(reduce(mul, (f for f, _ in factors if _ == k)), k)                   for k in set(i for _, i in factors)]</ins>      return coeff, factors


Question: elif self.exp.is_extended_nonpositive:                 return False         elif self.base.is_zero is False:            if self.exp.is_negative:            if self.base.is_finite and self.exp.is_finite:                return False            elif self.exp.is_negative:                 return self.base.is_infinite             elif self.exp.is_nonnegative:                 return False            elif self.exp.is_infinite:            elif self.exp.is_infinite and self.exp.is_extended_real:                 if (1 - abs(self.base)).is_extended_positive:                     return self.exp.is_extended_positive                 elif (1 - abs(self.base)).is_extended_negative:                     return self.exp.is_extended_negative        else:            # when self.base.is_zero is None            return None        else: # when self.base.is_zero is None            if self.base.is_finite and self.exp.is_negative:                return False      def _eval_is_integer(self):         b, e = self.args

Fix iszero and ispositive for Pow <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. ". See . Please also write a comment on that issue linking back to this pull request once it is open. -- Still a work in progress. This attempts to get working in all cases. This PR fixes so that it doesn't assume finiteness unless justified by assumptions. For example on master: This is incorrect because if a or b can be infinite then it is possible for to be zero e.g. if is infinite and b is negative (a)<1 and b is positive infinite (oo) (a)1 and b is negative infinite (-oo) With this PR we have meaning that could be zero or could not be zero. Also on master we have whereas this PR gives in that case since could be zero and therefore not be positive. This PR also since This comes from the fact that is properly considered nonzero if is declared as finite. At the time of writing we still have this problem with the PR though: I'm not sure that this PR should be merged as is. Many of the changes are adding flags that probably shouldn't be there. Those flags would not be necessary if the other assumptions implied finite=True. For example in some cases a symbol is declared as and with this PR I've had to add also. Probably it would be better to fix those cases by having in the assumptions system. Most of the other cases are for symbols declared as which could also be fixed. Now that I (hopefully) have the tests passing I still want to improve this PR by tidying up the implementation. Also it still doesn't work in all cases as the zoo/n example above shows. Perhaps instead of merging this I could build new PRs on top. One could add . Then I could follow that with splitting real into extendedreal and real and having as well. That would be a big change though so maybe it would be better to merge this first. <!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --core Fix iszero assumptions for and when or could be infinite. <!-- END RELEASE NOTES --


Question: if real_b is False:  # we already know it's not imag             i = arg(self.base)*self.exp/S.Pi            return i.is_integer            if i.is_complex: # finite                return i.is_integer      def _eval_is_complex(self):


Question: latex_new = (self._print(e) for e in new)         latex_subs = r'\\ '.join(             e[0] + '=' + e[1] for e in zip(latex_old, latex_new))        return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr,        return r'\left. \left(%s\right) \right|_{\substack{ %s }}' % (latex_expr,                                                          latex_subs)      def _print_Integral(self, expr):

Incorrect parenthesizing of Subs Here is an example. LaTeX printing of this gives: ! It would be better to be parenthesized to: !


Question: """     is_HadamardProduct = True     def __new__(cls, *args, **kwargs):    def __new__(cls, *args, evaluate=False, **kwargs):         args = list(map(sympify, args))         check = kwargs.get('check', True)         if check:             validate(*args)         return super(HadamardProduct, cls).__new__(cls, *args)        obj = super(HadamardProduct, cls).__new__(cls, *args)        if evaluate:            obj = obj.doit(deep=False)        return obj      @property     def shape(self):diff --git a/sympy/matrices/expressions/matadd.py b/sympy/matrices/expressions/matadd.py-- a/sympy/matrices/expressions/matadd.py++ b/sympy/matrices/expressions/matadd.py

Introduce 'evaluate' keyword argument in MatAdd and MatMul . Here is an example: I believe it would be better to add option which canonicallizes the object, so that


Question: identity = GenericZeroMatrix()     def __new__(cls, *args, **kwargs):    def __new__(cls, *args, evaluate=False, **kwargs):         if not args:             return cls.identity


Question: check = kwargs.get('check', False)          obj = Basic.__new__(cls, *args)         if check:             if all(not isinstance(i, MatrixExpr) for i in args):                 return Add.fromiter(args)             validate(*args)        if evaluate:            if all(not isinstance(i, MatrixExpr) for i in args):                return Add(*args, evaluate=True)            obj = canonicalize(obj)         return obj      @propertydiff --git a/sympy/matrices/expressions/matmul.py b/sympy/matrices/expressions/matmul.py-- a/sympy/matrices/expressions/matmul.py++ b/sympy/matrices/expressions/matmul.py