Question: def factorial_notation(tokens, local_dict, global_dict):     """Allows standard notation for factorial."""     result = []    prevtoken = ''    nfactorial = 0     for toknum, tokval in tokens:        if toknum == OP:        if toknum == ERRORTOKEN:             op = tokval            if op == '!!':                if prevtoken == '!' or prevtoken == '!!':                    raise TokenError                result = _add_factorial_tokens('factorial2', result)            elif op == '!':                if prevtoken == '!' or prevtoken == '!!':                    raise TokenError                result = _add_factorial_tokens('factorial', result)            if op == '!':                nfactorial += 1             else:                nfactorial = 0                 result.append((OP, op))         else:            if nfactorial == 1:                result = _add_factorial_tokens('factorial', result)            elif nfactorial == 2:                result = _add_factorial_tokens('factorial2', result)            elif nfactorial > 2:                raise TokenError            nfactorial = 0             result.append((toknum, tokval))        prevtoken = tokval     return result


Question: return result def repeated_decimals(tokens, local_dict, global_dict):    """    Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)    Run this before auto_number.    """    result = []    def is_digit(s):        return all(i in '0123456789_' for i in s)    # num will running match any DECIMAL [ INTEGER ]    num = []    for toknum, tokval in tokens:        if toknum == NUMBER:            if (not num and '.' in tokval and 'e' not in tokval.lower() and                'j' not in tokval.lower()):                num.append((toknum, tokval))            elif is_digit(tokval)and  len(num) == 2:                num.append((toknum, tokval))            elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]):                # Python 2 tokenizes 00123 as '00', '123'                # Python 3 tokenizes 01289 as '012', '89'                num.append((toknum, tokval))            else:                num = []        elif toknum == OP:            if tokval == '[' and len(num) == 1:                num.append((OP, tokval))            elif tokval == ']' and len(num) >= 3:                num.append((OP, tokval))            elif tokval == '.' and not num:                # handle .[1]                num.append((NUMBER, '0.'))            else:                num = []        else:            num = []        result.append((toknum, tokval))        if num and num[-1][1] == ']':            # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post,            # and d/e = repetend            result = result[:-len(num)]            pre, post = num[0][1].split('.')            repetend = num[2][1]            if len(num) == 5:                repetend += num[3][1]            pre = pre.replace('_', '')            post = post.replace('_', '')            repetend = repetend.replace('_', '')            zeros = '0'*len(post)            post, repetends = [w.lstrip('0') for w in [post, repetend]]                                        # or else interpreted as octal            a = pre or '0'            b, c = post or '0', '1' + zeros            d, e = repetends, ('9'*len(repetend)) + zeros            seq = [                (OP, '('),                    (NAME, 'Integer'),                    (OP, '('),                        (NUMBER, a),                    (OP, ')'),                    (OP, '+'),                    (NAME, 'Rational'),                    (OP, '('),                        (NUMBER, b),                        (OP, ','),                        (NUMBER, c),                    (OP, ')'),                    (OP, '+'),                    (NAME, 'Rational'),                    (OP, '('),                        (NUMBER, d),                        (OP, ','),                        (NUMBER, e),                    (OP, ')'),                (OP, ')'),            ]            result.extend(seq)            num = []    return result  def auto_number(tokens, local_dict, global_dict):    """Converts numeric literals to use SymPy equivalents.    """    Converts numeric literals to use SymPy equivalents.     Complex numbers use ``I``; integer literals use ``Integer``, float    literals use ``Float``, and repeating decimals use ``Rational``.    Complex numbers use ``I``, integer literals use ``Integer``, and float    literals use ``Float``.      """     result = []    prevtoken = ''      for toknum, tokval in tokens:         if toknum == NUMBER:

sympify(u"α") does not work Original issue for : Original author: Original owner:


Question: if '.' in number or (('e' in number or 'E' in number) and                     not (number.startswith('0x') or number.startswith('0X'))):                match = _re_repeated.match(number)                if match is not None:                    # Clear repeating decimals, e.g. 3.4[31] -> (3 + 4/10 + 31/990)                    pre, post, repetend = match.groups()                    zeros = '0'*len(post)                    post, repetends = [w.lstrip('0') for w in [post, repetend]]                                                # or else interpreted as octal                    a = pre or '0'                    b, c = post or '0', '1' + zeros                    d, e = repetends, ('9'*len(repetend)) + zeros                    seq = [                        (OP, '('),                        (NAME,                         'Integer'), (OP, '('), (NUMBER, a), (OP, ')'),                        (OP, '+'),                        (NAME, 'Rational'), (OP, '('), (                            NUMBER, b), (OP, ','), (NUMBER, c), (OP, ')'),                        (OP, '+'),                        (NAME, 'Rational'), (OP, '('), (                            NUMBER, d), (OP, ','), (NUMBER, e), (OP, ')'),                        (OP, ')'),                    ]                else:                    seq = [(NAME, 'Float'), (OP, '('),                           (NUMBER, repr(str(number))), (OP, ')')]                seq = [(NAME, 'Float'), (OP, '('),                    (NUMBER, repr(str(number))), (OP, ')')]             else:                 seq = [(NAME, 'Integer'), (OP, '('), (                     NUMBER, number), (OP, ')')]


Question: return result <del></del> def rationalize(tokens, local_dict, global_dict):     """Converts floats into ``Rational``. Run AFTER ``auto_number``."""     result = []


Question: #: Standard transformations for :func:`parse_expr`. #: Inserts calls to :class:`Symbol`, :class:`Integer`, and other SymPy #: datatypes and allows the use of standard factorial notation (e.g. ``x!``).standard_transformations = (lambda_notation, auto_symbol, auto_number, factorial_notation)standard_transformations = (lambda_notation, auto_symbol, repeated_decimals, auto_number,    factorial_notation)   def stringify_expr(s, local_dict, global_dict, transformations):diff --git a/sympy/parsing/sympy_tokenize.py b/sympy/parsing/sympy_tokenize.pydeleted file mode 100644-- a/sympy/parsing/sympy_tokenize.py++ /dev/null


Question: <del>"""Tokenization help for Python programs.generate_tokens(readline) is a generator that breaks a stream oftext into Python tokens.  It accepts a readline-like method which is calledrepeatedly to get the next line of input (or "" for EOF).  It generates5-tuples with these members:    the token type (see token.py)    the token (a string)    the starting (row, column) indices of the token (a 2-tuple of ints)    the ending (row, column) indices of the token (a 2-tuple of ints)    the original line (string)It is designed to match the working of the Python tokenizer exactly, exceptthat it produces COMMENT tokens for comments and gives type OP for alloperatorsOlder entry points    tokenize_loop(readline, tokeneater)    tokenize(readline, tokeneater=printtoken)are the same, except instead of generating tokens, tokeneater is a callbackfunction to which the 5 fields described above are passed as 5 arguments,each time a new token is found."""from __future__ import print_function, division__author__ = 'Ka-Ping Yee <ping@lfw.org>'__credits__ = \    'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger'import stringimport refrom token import *import token__all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize",           "generate_tokens", "NL", "untokenize"]del tokenCOMMENT = N_TOKENStok_name[COMMENT] = 'COMMENT'NL = N_TOKENS + 1tok_name[NL] = 'NL'N_TOKENS += 2def group(*choices):    return '(' + '|'.join(choices) + ')'def any(*choices):    return group(*choices) + '*'def maybe(*choices):    return group(*choices) + '?'Whitespace = r'[ \f\t]*'Comment = r'#[^\r\n]*'Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)Name = r'[a-zA-Z_]\w*'Hexnumber = r'0[xX][\da-fA-F]+[lL]?'Octnumber = r'(0[oO][0-7]+)|(0[0-7]*)[lL]?'Binnumber = r'0[bB][01]+[lL]?'Decnumber = r'[1-9]\d*[lL]?'Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)Exponent = r'[eE][-+]?\d+'Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)Repeatedfloat = r'\d*\.\d*\[\d+\]'Expfloat = r'\d+' + ExponentFloatnumber = group(Repeatedfloat, Pointfloat, Expfloat)Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]')Number = group(Imagnumber, Floatnumber, Intnumber)# Tail end of ' string.Single = r"[^'\\]*(?:\\.[^'\\]*)*'"# Tail end of " string.Double = r'[^"\\]*(?:\\.[^"\\]*)*"'# Tail end of ''' string.Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"# Tail end of """ string.Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""')# Single-line ' or " string.String = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",               r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')# Because of leftmost-then-longest match semantics, be sure to put the# longest operators first (e.g., if = came before ==, == would get# recognized as two instances of =).Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",                 r"//=?",                 r"[+\-*/%&|^=<>]=?",                 r"~")Bracket = '[][(){}]'Special = group(r'\r?\n', r'[:;.,`@]', r'\!\!', r'\!')Funny = group(Operator, Bracket, Special)PlainToken = group(Number, Funny, String, Name)Token = Ignore + PlainToken# First (or only) line of ' or " string.ContStr = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" +                group("'", r'\\\r?\n'),                r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' +                group('"', r'\\\r?\n'))PseudoExtras = group(r'\\\r?\n', Comment, Triple)PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)tokenprog, pseudoprog, single3prog, double3prog = map(    re.compile, (Token, PseudoToken, Single3, Double3))endprogs = {"'": re.compile(Single), '"': re.compile(Double),            "'''": single3prog, '"""': double3prog,            "r'''": single3prog, 'r"""': double3prog,            "u'''": single3prog, 'u"""': double3prog,            "ur'''": single3prog, 'ur"""': double3prog,            "R'''": single3prog, 'R"""': double3prog,            "U'''": single3prog, 'U"""': double3prog,            "uR'''": single3prog, 'uR"""': double3prog,            "Ur'''": single3prog, 'Ur"""': double3prog,            "UR'''": single3prog, 'UR"""': double3prog,            "b'''": single3prog, 'b"""': double3prog,            "br'''": single3prog, 'br"""': double3prog,            "B'''": single3prog, 'B"""': double3prog,            "bR'''": single3prog, 'bR"""': double3prog,            "Br'''": single3prog, 'Br"""': double3prog,            "BR'''": single3prog, 'BR"""': double3prog,            'r': None, 'R': None, 'u': None, 'U': None,            'b': None, 'B': None}triple_quoted = {}for t in ("'''", '"""',          "r'''", 'r"""', "R'''", 'R"""',          "u'''", 'u"""', "U'''", 'U"""',          "ur'''", 'ur"""', "Ur'''", 'Ur"""',          "uR'''", 'uR"""', "UR'''", 'UR"""',          "b'''", 'b"""', "B'''", 'B"""',          "br'''", 'br"""', "Br'''", 'Br"""',          "bR'''", 'bR"""', "BR'''", 'BR"""'):    triple_quoted[t] = tsingle_quoted = {}for t in ("'", '"',          "r'", 'r"', "R'", 'R"',          "u'", 'u"', "U'", 'U"',          "ur'", 'ur"', "Ur'", 'Ur"',          "uR'", 'uR"', "UR'", 'UR"',          "b'", 'b"', "B'", 'B"',          "br'", 'br"', "Br'", 'Br"',          "bR'", 'bR"', "BR'", 'BR"' ):    single_quoted[t] = ttabsize = 8class TokenError(Exception):    passclass StopTokenizing(Exception):    passdef printtoken(type, token, srow_scol, erow_ecol, line):  # for testing    srow, scol = srow_scol    erow, ecol = erow_ecol    print("%d,%d-%d,%d:\t%s\t%s" % \        (srow, scol, erow, ecol, tok_name[type], repr(token)))def tokenize(readline, tokeneater=printtoken):    """    The tokenize() function accepts two parameters: one representing the    input stream, and one providing an output mechanism for tokenize().    The first parameter, readline, must be a callable object which provides    the same interface as the readline() method of built-in file objects.    Each call to the function should return one line of input as a string.    The second parameter, tokeneater, must also be a callable object. It is    called once for each token, with five arguments, corresponding to the    tuples generated by generate_tokens().    """    try:        tokenize_loop(readline, tokeneater)    except StopTokenizing:        pass# backwards compatible interfacedef tokenize_loop(readline, tokeneater):    for token_info in generate_tokens(readline):        tokeneater(*token_info)class Untokenizer:    def __init__(self):        self.tokens = []        self.prev_row = 1        self.prev_col = 0    def add_whitespace(self, start):        row, col = start        if row > self.prev_row:            raise ValueError("row should not be greater than prev_row")        col_offset = col - self.prev_col        if col_offset:            self.tokens.append(" " * col_offset)    def untokenize(self, iterable):        for t in iterable:            if len(t) == 2:                self.compat(t, iterable)                break            tok_type, token, start, end, line = t            self.add_whitespace(start)            self.tokens.append(token)            self.prev_row, self.prev_col = end            if tok_type in (NEWLINE, NL):                self.prev_row += 1                self.prev_col = 0        return "".join(self.tokens)    def compat(self, token, iterable):        startline = False        indents = []        toks_append = self.tokens.append        toknum, tokval = token        if toknum in (NAME, NUMBER):            tokval += ' '        if toknum in (NEWLINE, NL):            startline = True        prevstring = False        for tok in iterable:            toknum, tokval = tok[:2]            if toknum in (NAME, NUMBER):                tokval += ' '            # Insert a space between two consecutive strings            if toknum == STRING:                if prevstring:                    tokval = ' ' + tokval                prevstring = True            else:                prevstring = False            if toknum == INDENT:                indents.append(tokval)                continue            elif toknum == DEDENT:                indents.pop()                continue            elif toknum in (NEWLINE, NL):                startline = True            elif startline and indents:                toks_append(indents[-1])                startline = False            toks_append(tokval)def untokenize(iterable):    """Transform tokens back into Python source code.    Each element returned by the iterable must be a token sequence    with at least two elements, a token number and token value.  If    only two tokens are passed, the resulting output is poor.    Round-trip invariant for full input:        Untokenized source will match input source exactly    Round-trip invariant for limited intput::        # Output text will tokenize the back to the input        t1 = [tok[:2] for tok in generate_tokens(f.readline)]        newcode = untokenize(t1)        readline = iter(newcode.splitlines(1)).next        t2 = [tok[:2] for tok in generate_tokens(readline)]        if t1 != t2:            raise ValueError("t1 should be equal to t2")    """    ut = Untokenizer()    return ut.untokenize(iterable)def generate_tokens(readline):    """    The generate_tokens() generator requires one argument, readline, which    must be a callable object which provides the same interface as the    readline() method of built-in file objects. Each call to the function    should return one line of input as a string.  Alternately, readline    can be a callable function terminating with StopIteration::        readline = open(myfile).next    # Example of alternate readline    The generator produces 5-tuples with these members: the token type; the    token string; a 2-tuple (srow, scol) of ints specifying the row and    column where the token begins in the source; a 2-tuple (erow, ecol) of    ints specifying the row and column where the token ends in the source;    and the line on which the token was found. The line passed is the    logical line; continuation lines are included.    """    lnum = parenlev = continued = 0    namechars, numchars = string.ascii_letters + '_', '0123456789'    contstr, needcont = '', 0    contline = None    indents = [0]    while 1:                                   # loop over lines in stream        try:            line = readline()        except StopIteration:            line = ''        lnum = lnum + 1        pos, max = 0, len(line)        if contstr:                            # continued string            if not line:                raise TokenError("EOF in multi-line string", strstart)            endmatch = endprog.match(line)            if endmatch:                pos = end = endmatch.end(0)                yield (STRING, contstr + line[:end],                       strstart, (lnum, end), contline + line)                contstr, needcont = '', 0                contline = None            elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':                yield (ERRORTOKEN, contstr + line,                       strstart, (lnum, len(line)), contline)                contstr = ''                contline = None                continue            else:                contstr = contstr + line                contline = contline + line                continue        elif parenlev == 0 and not continued:  # new statement            if not line:                break            column = 0            while pos < max:                   # measure leading whitespace                if line[pos] == ' ':                    column = column + 1                elif line[pos] == '\t':                    column = (column/tabsize + 1)*tabsize                elif line[pos] == '\f':                    column = 0                else:                    break                pos = pos + 1            if pos == max:                break            if line[pos] in '#\r\n':           # skip comments or blank lines                if line[pos] == '#':                    comment_token = line[pos:].rstrip('\r\n')                    nl_pos = pos + len(comment_token)                    yield (COMMENT, comment_token,                           (lnum, pos), (lnum, pos + len(comment_token)), line)                    yield (NL, line[nl_pos:],                           (lnum, nl_pos), (lnum, len(line)), line)                else:                    yield ((NL, COMMENT)[line[pos] == '#'], line[pos:],                           (lnum, pos), (lnum, len(line)), line)                continue            if column > indents[-1]:           # count indents or dedents                indents.append(column)                yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)            while column < indents[-1]:                if column not in indents:                    raise IndentationError(                        "unindent does not match any outer indentation level",                        ("<tokenize>", lnum, pos, line))                indents = indents[:-1]                yield (DEDENT, '', (lnum, pos), (lnum, pos), line)        else:                                  # continued statement            if not line:                raise TokenError("EOF in multi-line statement", (lnum, 0))            continued = 0        while pos < max:            pseudomatch = pseudoprog.match(line, pos)            if pseudomatch:                                # scan for tokens                start, end = pseudomatch.span(1)                spos, epos, pos = (lnum, start), (lnum, end), end                token, initial = line[start:end], line[start]                if initial in numchars or \                        (initial == '.' and token != '.'):      # ordinary number                    yield (NUMBER, token, spos, epos, line)                elif initial in '\r\n':                    yield (NL if parenlev > 0 else NEWLINE, token, spos, epos, line)                elif initial == '#':                    if token.endswith("\n"):                        raise ValueError("Token should not end with \n")                    yield (COMMENT, token, spos, epos, line)                elif token in triple_quoted:                    endprog = endprogs[token]                    endmatch = endprog.match(line, pos)                    if endmatch:                           # all on one line                        pos = endmatch.end(0)                        token = line[start:pos]                        yield (STRING, token, spos, (lnum, pos), line)                    else:                        strstart = (lnum, start)           # multiple lines                        contstr = line[start:]                        contline = line                        break                elif initial in single_quoted or \                    token[:2] in single_quoted or \                        token[:3] in single_quoted:                    if token[-1] == '\n':                  # continued string                        strstart = (lnum, start)                        endprog = (endprogs[initial] or endprogs[token[1]] or                                   endprogs[token[2]])                        contstr, needcont = line[start:], 1                        contline = line                        break                    else:                                  # ordinary string                        yield (STRING, token, spos, epos, line)                elif initial in namechars:                 # ordinary name                    yield (NAME, token, spos, epos, line)                elif initial == '\\':                      # continued stmt                    continued = 1                else:                    if initial in '([{':                        parenlev = parenlev + 1                    elif initial in ')]}':                        parenlev = parenlev - 1                    yield (OP, token, spos, epos, line)            else:                yield (ERRORTOKEN, line[pos],                       (lnum, pos), (lnum, pos + 1), line)                pos = pos + 1    for indent in indents[1:]:                 # pop remaining indent levels        yield (DEDENT, '', (lnum, 0), (lnum, 0), '')    yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')if __name__ == '__main__':                     # testing    import sys    if len(sys.argv) > 1:        tokenize(open(sys.argv[1]).readline)    else:        tokenize(sys.stdin.readline)</del>


Question: c = self._print(e.args[0])                 c = prettyForm(*c.parens())                 pform = a**b                pform = stringPict(*pform.right(' '))                pform = stringPict(*pform.right(c))                pform = prettyForm(*pform.right(' '))                pform = prettyForm(*pform.right(c))                 return pform             pform = self._print(e.args[0])             pform = prettyForm(*pform.parens())

pprint(x*DiracDelta(x, 1)) gives TypeError: unorderable types: NoneType() int() I bisected it to commit : CC


Question: s += self._print(expr.point)             else:                 s += self._print(expr.point[0])        return r"\mathcal{O}\left(%s\right)" % s        return r"O\left(%s\right)" % s      def _print_Symbol(self, expr):         if expr in self._settings['symbol_names']:

Typesetting of big-O symbol Currently typesetting of big-O symbol uses the ordinary 'O', we can use the typesetting as defined here .


Question: "mat_str": None,         "mat_delim": "[",         "symbol_names": {},<ins>        "ln_notation": False,</ins>     }      def __init__(self, settings=None):

Converting to LaTeX was converted to which is in some fields is log10(10) or log2(10). There is '\ln' in LaTeX and should be converted to it not to


Question: else:             return tex <ins>    def _print_log(self, expr, exp=None):        if not self._settings["ln_notation"]:            tex = r"\log{\left (%s \right )}" % self._print(expr.args[0])        else:            tex = r"\ln{\left (%s \right )}" % self._print(expr.args[0])        if exp is not None:            return r"%s^{%s}" % (tex, exp)        else:            return tex</ins>     def _print_Abs(self, expr, exp=None):         tex = r"\left|{%s}\right|" % self._print(expr.args[0])


Question: r"""     Convert the given expression to LaTeX representation.     >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational    >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log     >>> from sympy.abc import x, y, mu, r, tau      >>> print(latex((2*tau)**Rational(7,2)))


Question: >>> print(latex([2/x, y], mode='inline'))     $\left [ 2 / x, \quad y\right ]$ <ins>    ln_notation: If set to ``True`` "\ln" is used instead of default "\log"    >>> print(latex(log(10)))    \log{\left (10 \right )}    >>> print(latex(log(10), ln_notation=True))    \ln{\left (10 \right )}</ins>     """      return LatexPrinter(settings).doprint(expr)


Question: return r"%s^\dagger" % self._print(mat)      def _print_MatAdd(self, expr):        terms = list(expr.args)        tex = " + ".join(map(self._print, terms))        return tex        terms = [self._print(t) for t in expr.args]        l = []        for t in terms:            if t.startswith('-'):                sign = "-"                t = t[1:]            else:                sign = "+"            l.extend([sign, t])        sign = l.pop(0)        if sign == '+':            sign = ""        return sign + ' '.join(l)      def _print_MatMul(self, expr):        from sympy import Add, MatAdd, HadamardProduct        from sympy import Add, MatAdd, HadamardProduct, MatMul, Mul          def parens(x):             if isinstance(x, (Add, MatAdd, HadamardProduct)):                 return r"\left(%s\right)" % self._print(x)             return self._print(x)        return ' '.join(map(parens, expr.args))        if isinstance(expr, MatMul) and expr.args[0].is_Number and expr.args[0]<0:            expr = Mul(-1*expr.args[0], MatMul(*expr.args[1:]))            return '-' + ' '.join(map(parens, expr.args))        else:            return ' '.join(map(parens, expr.args))      def _print_Mod(self, expr, exp=None):         if exp is not None:diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py

The difference of MatrixSymbols prints as a sum with (-1) coefficient Internally, differences like a-b are represented as the sum of a with , but they are supposed to print like a-b. This does not happen with MatrixSymbols. I tried three printers: str, pretty, and latex: Output: Based on a


Question: return self._print(B.blocks)      def _print_MatAdd(self, expr):        return self._print_seq(expr.args, None, None, ' + ')        s = None        for item in expr.args:            pform = self._print(item)            if s is None:                s = pform     # First element            else:                if S(item.args[0]).is_negative:                    s = prettyForm(*stringPict.next(s, ' '))                    pform = self._print(item)                else:                    s = prettyForm(*stringPict.next(s, ' + '))                s = prettyForm(*stringPict.next(s, pform))        return s      def _print_MatMul(self, expr):         args = list(expr.args)diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


Question: return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)      def _print_MatMul(self, expr):        return '*'.join([self.parenthesize(arg, precedence(expr))        c, m = expr.as_coeff_mmul()        if c.is_number and c < 0:            expr = _keep_coeff(-c, m)            sign = "-"        else:            sign = ""        return sign + '*'.join([self.parenthesize(arg, precedence(expr))             for arg in expr.args])      def _print_HadamardProduct(self, expr):


Question: for arg in expr.args])      def _print_MatAdd(self, expr):        return ' + '.join([self.parenthesize(arg, precedence(expr))            for arg in expr.args])        terms = [self.parenthesize(arg, precedence(expr))             for arg in expr.args]        l = []        for t in terms:            if t.startswith('-'):                sign = "-"                t = t[1:]            else:                sign = "+"            l.extend([sign, t])        sign = l.pop(0)        if sign == '+':            sign = ""        return sign + ' '.join(l)      def _print_NaN(self, expr):         return 'nan'


Question: rep = DMP.from_list([1, 0], 0, dom)             scoeffs = Tuple(1, 0) <del>            if root.is_negative:                rep = -rep                scoeffs = Tuple(-1, 0)</del>         sargs = (root, scoeffs)          if alias is not None:

Sign of generator of an algebraic numberfield calls , but the implementation is defective as it does not change the minimal polynomial. I think this could be fixed in two ways: Add code to create the changed minimal polynomial. Ignore the sign and remove the code changing it. I am inclined to prefer the latter, simpler solution, but I would also like to hear other suggestions.


Question: #Fixing the newlines         lengths = []         strs = ['']        flag = []         for i, partstr in enumerate(o1):            flag.append(0)             # XXX: What is this hack?             if '\n' in partstr:                 tempstr = partstr                 tempstr = tempstr.replace(vectstrs[i], '')                tempstr = tempstr.replace(u'\N{RIGHT PARENTHESIS UPPER HOOK}',                                          u'\N{RIGHT PARENTHESIS UPPER HOOK}'                                          + ' ' + vectstrs[i])                if u'\N{right parenthesis extension}' in tempstr:   # If scalar is a fraction                    for paren in range(len(tempstr)):                        flag[i] = 1                        if tempstr[paren] == u'\N{right parenthesis extension}':                            tempstr = tempstr[:paren] + u'\N{right parenthesis extension}'\                                         + ' '  + vectstrs[i] + tempstr[paren + 1:]                            break                elif u'\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr:                    flag[i] = 1                    tempstr = tempstr.replace(u'\N{RIGHT PARENTHESIS LOWER HOOK}',                                        u'\N{RIGHT PARENTHESIS LOWER HOOK}'                                        + ' ' + vectstrs[i])                else:                    tempstr = tempstr.replace(u'\N{RIGHT PARENTHESIS UPPER HOOK}',                                        u'\N{RIGHT PARENTHESIS UPPER HOOK}'                                        + ' ' + vectstrs[i])                 o1[i] = tempstr         o1 = [x.split('\n') for x in o1]        n_newlines = max([len(x) for x in o1])        for parts in o1:            lengths.append(len(parts[0]))        n_newlines = max([len(x) for x in o1])  # Width of part in its pretty form        if 1 in flag:                           # If there was a fractional scalar            for i, parts in enumerate(o1):                if len(parts) == 1:             # If part has no newline                    parts.insert(0, ' ' * (len(parts[0])))                    flag[i] = 1        for i, parts in enumerate(o1):            lengths.append(len(parts[flag[i]]))             for j in range(n_newlines):                 if j+1 <= len(parts):                     if j >= len(strs):                         strs.append(' ' * (sum(lengths[:-1]) +                                            3*(len(lengths)-1)))                    if j == 0:                        strs[0] += parts[0] + ' + '                    if j == flag[i]:                        strs[flag[i]] += parts[flag[i]] + ' + '                     else:                         strs[j] += parts[j] + ' '*(lengths[-1] -                                                    len(parts[j])+

vectors break pretty printing Also, when it does print correctly, the baseline is wrong (it should be centered).


Question: def _print_Poly(self, poly):         cls = poly.__class__.__name__        expr = self._print(poly.as_expr())        terms = []        for monom, coeff in poly.terms():            s_monom = ''            for i, exp in enumerate(monom):                if exp > 0:                    if exp == 1:                        s_monom += self._print(poly.gens[i])                    else:                        s_monom += self._print(pow(poly.gens[i], exp))            if coeff.is_Add:                if s_monom:                    s_coeff = r"\left(%s\right)" % self._print(coeff)                else:                    s_coeff = self._print(coeff)            else:                if s_monom:                    if coeff is S.One:                        terms.extend(['+', s_monom])                        continue                    if coeff is S.NegativeOne:                        terms.extend(['-', s_monom])                        continue                s_coeff = self._print(coeff)            if not s_monom:                s_term = s_coeff            else:                s_term = s_coeff + " " + s_monom            if s_term.startswith('-'):                terms.extend(['-', s_term[1:]])            else:                terms.extend(['+', s_term])        if terms[0] in ['-', '+']:            modifier = terms.pop(0)            if modifier == '-':                terms[0] = '-' + terms[0]        expr = ' '.join(terms)         gens = list(map(self._print, poly.gens))         domain = "domain=%s" % self._print(poly.get_domain())

LaTeX printer does not use the same order of monomials as pretty and str When printing a Poly, the str and pretty printers use the logical order of monomials, from highest to lowest degrees. But latex printer does not.


Question: def mod_inverse(a, m):     """    Return the number c such that, ( a * c ) % m == 1 where    c has the same sign as a. If no such value exists, a    ValueError is raised.    Return the number c such that, (a * c) = 1 (mod m)    where c has the same sign as m. If no such value exists,    a ValueError is raised.      Examples     ========

Modular inverse for negative modulo and sign resolve SymPy assigns the same sign as . Mathematically, has range for , for . The former sign assignment is used in C/C++/Java built-in modulo operator as returns . The latter sign assignment is used in Python's built-in modulo operator as returns . SymPy does not find modular inverses for negative modulo (because of the check). Moreover, as checked from WA (uses the same sign as rule)


Question: Suppose we wish to find multiplicative inverse x of     3 modulo 11. This is the same as finding x such     that 3 * x = 1 (mod 11). One value of x that satisfies    this congruence is 4. Because 3 * 4 = 12 and 12 = 1 mod(11).    this congruence is 4. Because 3 * 4 = 12 and 12 = 1 (mod 11).     This is the value return by mod_inverse:      >>> mod_inverse(3, 11)     4     >>> mod_inverse(-3, 11)    -4    7      When there is a common factor between the numerators of     ``a`` and ``m`` the inverse does not exist:


Question: c = None     try:         a, m = as_int(a), as_int(m)        if m > 1:        if m != 1 and m != -1:             x, y, g = igcdex(a, m)             if g == 1:                 c = x % m            if a < 0:                c -= m     except ValueError:         a, m = sympify(a), sympify(m)         if not (a.is_number and m.is_number):


Question: _re_realfield = re.compile(r"^(R|RR)(_(\d+))?$")     _re_complexfield = re.compile(r"^(C|CC)(_(\d+))?$")     _re_finitefield = re.compile(r"^(FF|GF)\((\d+)\)$")    _re_polynomial = re.compile(r"^(Z|ZZ|Q|QQ)\[(.+)\]$")    _re_polynomial = re.compile(r"^(Z|ZZ|Q|QQ|R|RR|C|CC)\[(.+)\]$")     _re_fraction = re.compile(r"^(Z|ZZ|Q|QQ)\((.+)\)$")     _re_algebraic = re.compile(r"^(Q|QQ)\<(.+)\>$")

Poly(domain='RR[y,z]') doesn't work Also, the wording of error message could be improved


Question: if ground in ['Z', 'ZZ']:                     return sympy.polys.domains.ZZ.poly_ring(*gens)                else:                elif ground in ['Q', 'QQ']:                     return sympy.polys.domains.QQ.poly_ring(*gens)                elif ground in ['R', 'RR']:                    return sympy.polys.domains.RR.poly_ring(*gens)                else:                    return sympy.polys.domains.CC.poly_ring(*gens)              r = cls._re_fraction.match(domain)


Question: def _print_ConditionSet(self, s):         vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)])        return r"\left\{%s\; |\; %s \in %s \wedge %s \right\}" % (        if s.base_set is S.UniversalSet:            return r"\left\{%s \mid %s \right\}" % (            vars_print,            self._print(s.condition.as_expr()))        return r"\left\{%s \mid %s \in %s \wedge %s \right\}" % (             vars_print,             vars_print,             self._print(s.base_set),diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py

ambiguous behavior of ConditionSet Does that mean the "set of all x in S for which condition(x) is True" or "the set S if the condition(x) is True"? Also, should there be a doit method or autoevaluation for something like this? Other fixes: should be S.EmptySet should be unchanged: the dummy is not there to help with the condition, only to test idientify where the element from the base_set should be tested in the condition.


Question: cond = self._print_seq(cond, "(", ")")          bar = self._print("|")        base = self._print(ts.base_set)         if ts.base_set is S.UniversalSet:            return self._print_seq((variables, bar, cond), "{", "}", ' ')        base = self._print(ts.base_set)         return self._print_seq((variables, bar, variables, inn,                                 base, _and, cond), "{", "}", ' ') diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


Question: def _print_ComplexInfinity(self, expr):         return 'zoo'     def _print_ConditionSet(self, s):        args = tuple([self._print(i) for i in (s.sym, s.condition)])        if s.base_set is S.UniversalSet:            return 'ConditionSet(%s, %s)' % args        args += (self._print(s.base_set),)        return 'ConditionSet(%s, %s, %s)' % args     def _print_Derivative(self, expr):         dexpr = expr.expr         dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count]diff --git a/sympy/sets/conditionset.py b/sympy/sets/conditionset.py-- a/sympy/sets/conditionset.py++ b/sympy/sets/conditionset.py


Question: from __future__ import print_function, division  from sympy import Sfrom sympy.sets.contains import Contains from sympy.core.basic import Basic from sympy.core.containers import Tuplefrom sympy.core.expr import Expr from sympy.core.function import Lambda from sympy.core.logic import fuzzy_bool from sympy.core.symbol import Symbol, Dummy


Question: from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,                              FiniteSet) from sympy.utilities.iterables import sift<ins>from sympy.utilities.misc import filldedent</ins> from sympy.multipledispatch import dispatch


Question: ========      >>> from sympy import Symbol, S, ConditionSet, pi, Eq, sin, Interval    >>> x = Symbol('x')    >>> from sympy.abc import x, y, z     >>> sin_sols = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi))     >>> 2*pi in sin_sols     True


Question: False     >>> 5 in ConditionSet(x, x**2 > 4, S.Reals)     True    If the value is not in the base set, the result is false:    >>> 5 in ConditionSet(x, x**2 > 4, Interval(2, 4))    False    Notes    =====    Symbols with assumptions should be avoided or else the    condition may evaluate without consideration of the set:    >>> n = Symbol('n', negative=True)    >>> cond = (n > 0); cond    False    >>> ConditionSet(n, cond, S.Integers)    EmptySet()    In addition, substitution of a dummy symbol can only be    done with a generic symbol with matching commutativity    or else a symbol that has identical assumptions. If the    base set contains the dummy symbol it is logically distinct    and will be the target of substitution.    >>> c = ConditionSet(x, x < 1, {x, z})    >>> c.subs(x, y)    ConditionSet(x, x < 1, {y, z})    A second substitution is needed to change the dummy symbol, too:    >>> _.subs(x, y)    ConditionSet(y, y < 1, {y, z})    And trying to replace the dummy symbol with anything but a symbol    is ignored: the only change possible will be in the base set:    >>> ConditionSet(y, y < 1, {y, z}).subs(y, 1)    ConditionSet(y, y < 1, {z})    >>> _.subs(y, 1)    ConditionSet(y, y < 1, {z})    Notes    =====    If no base set is specified, the universal set is implied:    >>> ConditionSet(x, x < 1).base_set    UniversalSet()    Although expressions other than symbols may be used, this    is discouraged and will raise an error if the expression    is not found in the condition:    >>> ConditionSet(x + 1, x + 1 < 1, S.Integers)    ConditionSet(x + 1, x + 1 < 1, S.Integers)    >>> ConditionSet(x + 1, x < 1, S.Integers)    Traceback (most recent call last):    ...    ValueError: non-symbol dummy not recognized in condition    Although the name is usually respected, it must be replaced if    the base set is another ConditionSet and the dummy symbol    and appears as a free symbol in the base set and the dummy symbol    of the base set appears as a free symbol in the condition:    >>> ConditionSet(x, x < y, ConditionSet(y, x + y < 2, S.Integers))    ConditionSet(lambda, (lambda < y) & (lambda + x < 2), S.Integers)    The best way to do anything with the dummy symbol is to access    it with the sym property.    >>> _.subs(_.sym, Symbol('_x'))    ConditionSet(_x, (_x < y) & (_x + x < 2), S.Integers)     """    def __new__(cls, sym, condition, base_set):    def __new__(cls, sym, condition, base_set=S.UniversalSet):         # nonlinsolve uses ConditionSet to return an unsolved system         # of equations (see _return_conditionset in solveset) so until         # that is changed we do minimal checking of the args        unsolved = isinstance(sym, (Tuple, tuple))        if unsolved:        if isinstance(sym, (Tuple, tuple)):  # unsolved eqns syntax             sym = Tuple(*sym)             condition = FiniteSet(*condition)        else:            condition = as_Boolean(condition)            return Basic.__new__(cls, sym, condition, base_set)        condition = as_Boolean(condition)         if isinstance(base_set, set):             base_set = FiniteSet(*base_set)         elif not isinstance(base_set, Set):             raise TypeError('expecting set for base_set')        if condition == S.false:        if condition is S.false:             return S.EmptySet        if condition == S.true:        if condition is S.true:             return base_set         if isinstance(base_set, EmptySet):             return base_set        if not unsolved:            if isinstance(base_set, FiniteSet):                sifted = sift(                    base_set, lambda _: fuzzy_bool(                        condition.subs(sym, _)))                if sifted[None]:                    return Union(FiniteSet(*sifted[True]),                        Basic.__new__(cls, sym, condition,                        FiniteSet(*sifted[None])))                else:                    return FiniteSet(*sifted[True])            if isinstance(base_set, cls):                s, c, base_set = base_set.args                if sym == s:                    condition = And(condition, c)                elif sym not in c.free_symbols:                    condition = And(condition, c.xreplace({s: sym}))                elif s not in condition.free_symbols:                    condition = And(condition.xreplace({sym: s}), c)                    sym = s                else:                    # user will have to use cls.sym to get symbol                    dum = Symbol('lambda')                    if dum in condition.free_symbols or \                            dum in c.free_symbols:                        dum = Dummy(str(dum))                    condition = And(                        condition.xreplace({sym: dum}),                        c.xreplace({s: dum}))                    sym = dum            if sym in base_set.free_symbols or \                    not isinstance(sym, Symbol):                s = Symbol('lambda')                if s in base_set.free_symbols:                    s = Dummy('lambda')                condition = condition.xreplace({sym: s})        know = None        if isinstance(base_set, FiniteSet):            sifted = sift(                base_set, lambda _: fuzzy_bool(                    condition.subs(sym, _)))            if sifted[None]:                know = FiniteSet(*sifted[True])                base_set = FiniteSet(*sifted[None])            else:                return FiniteSet(*sifted[True])        if isinstance(base_set, cls):            s, c, base_set = base_set.args            if sym == s:                condition = And(condition, c)            elif sym not in c.free_symbols:                condition = And(condition, c.xreplace({s: sym}))            elif s not in condition.free_symbols:                condition = And(condition.xreplace({sym: s}), c)                 sym = s        return Basic.__new__(cls, sym, condition, base_set)            else:                # user will have to use cls.sym to get symbol                dum = Symbol('lambda')                if dum in condition.free_symbols or \                        dum in c.free_symbols:                    dum = Dummy(str(dum))                condition = And(                    condition.xreplace({sym: dum}),                    c.xreplace({s: dum}))                sym = dum        if not isinstance(sym, Symbol):            s = Dummy('lambda')            if s not in condition.xreplace({sym: s}).free_symbols:                raise ValueError(                    'non-symbol dummy not recognized in condition')        rv = Basic.__new__(cls, sym, condition, base_set)        return rv if know is None else Union(know, rv)      sym = property(lambda self: self.args[0])     condition = property(lambda self: self.args[1])


Question: other), self.base_set.contains(other))      def _eval_subs(self, old, new):        if not isinstance(self.sym, Symbol):        if not isinstance(self.sym, Expr):             # Don't do anything with the equation set syntax;             # that should go away, eventually.             return self        if old == self.sym:            if new not in self.free_symbols:                if isinstance(new, Symbol):                    return self.func(*[i.subs(old, new) for i in self.args])            return self.func(self.sym, self.condition, self.base_set.subs(old, new))        return self.func(*([self.sym] + [i.subs(old, new) for i in self.args[1:]]))        sym, cond, base = self.args        if old == sym:            # we try to be as lenient as possible to allow            # the dummy symbol to be changed            base = base.subs(old, new)            if isinstance(new, Symbol):                # if the assumptions don't match, the cond                # might evaluate or change                if (new.assumptions0 == old.assumptions0 or                        len(new.assumptions0) == 1 and                        old.is_commutative == new.is_commutative):                    if base != self.base_set:                        # it will be aggravating to have the dummy                        # symbol change if you are trying to target                        # the base set so if the base set is changed                        # leave the dummy symbol alone -- a second                        # subs will be needed to change the dummy                        return self.func(sym, cond, base)                    else:                        return self.func(new, cond.subs(old, new), base)                raise ValueError(filldedent('''                    A dummy symbol can only be                    replaced with a symbol having the same                    assumptions or one having a single assumption                    having the same commutativity.                '''))            # don't target cond: it is there to tell how            # the base set should be filtered and if new is not in            # the base set then this substitution is ignored            return self.func(sym, cond, base)        cond = self.condition.subs(old, new)        base = self.base_set.subs(old, new)        if cond is S.true:            return ConditionSet(new, Contains(new, base), base)        return self.func(self.sym, cond, base)      def dummy_eq(self, other, symbol=None):         if not isinstance(other, self.func):


Question: @classmethod     def eval(cls, n, k):         n, k = map(sympify, (n, k))        d = n - k        if d.is_zero or k.is_zero:        if k.is_zero:             return S.One         if (k - 1).is_zero:             return n         if k.is_integer:            if k.is_negative:            if k.is_negative or (n.is_integer and n.is_nonnegative                    and (n - k).is_negative):                 return S.Zero            if n.is_integer and n.is_nonnegative and d.is_negative:                return S.Zero            if n.is_number:            elif n.is_number:                 res = cls._eval(n, k)                 return res.expand(basic=True) if res else res        elif n.is_negative and n.is_integer and not k.is_integer:        elif n.is_negative and n.is_integer:             # a special case when binomial evaluates to complex infinity             return S.ComplexInfinity         elif k.is_number:

Incorrect binomial documentation The for states: This is the usual definition of the binomial coefficient, but the implementation does not follow this. To be exact, returns , even for negative . See . For example: ` It shouldn't be hard to fix this either way (changing the documentation or the conditionals in ). Is there a preference as to which one should change?


Question: @classmethod     def eval(cls, n, k):         n, k = map(sympify, (n, k))        if k.is_zero:        d = n - k        n_nonneg, n_isint = n.is_nonnegative, n.is_integer        if k.is_zero or ((n_nonneg or n_isint == False)                and d.is_zero):             return S.One        if (k - 1).is_zero:        if (k - 1).is_zero or ((n_nonneg or n_isint == False)                and (d - 1).is_zero):             return n         if k.is_integer:            if k.is_negative or (n.is_integer and n.is_nonnegative                    and (n - k).is_negative):            if k.is_negative or (n_nonneg and n_isint and d.is_negative):                 return S.Zero             elif n.is_number:                 res = cls._eval(n, k)                 return res.expand(basic=True) if res else res        elif n.is_negative and n.is_integer:        elif n_nonneg == False and n_isint:             # a special case when binomial evaluates to complex infinity             return S.ComplexInfinity         elif k.is_number:

binomial(n,n) needs simplify to become 1 After , does not become 1. Sure. But even with appropriate assumptions, we need to simplify: was that intentional? Maybe its not important given that DTRT with ... Thoughts?


Question: """         newframe = self.__class__(newname, variables, indices, latexs)        newframe = self.__class__(newname, variables=variables,                                  indices=indices, latexs=latexs)         newframe.orient(self, rot_type, amounts, rot_order)         return newframe

orientnew in sympy.physics.mechanics does not support indices Original issue for : Original author:


Question: len(args) == 1 and \                 not self._needs_function_brackets(expr.args[0])             inv_trig_table = ["asin", "acos", "atan", "acot"]            inv_trig_table = ["asin", "acos", "atan", "acsc", "asec", "acot"]              # If the function is an inverse trig function, handle the style             if func in inv_trig_table:

Latex printer does not support full inverse trig function names for acsc and asec For example works as expected returning But gives instead of A fix seems to be to change line 743 of from to


Question: if s is None:                 s = pform     # First element             else:                if S(item.args[0]).is_negative:                coeff = item.as_coeff_mmul()[0]                if _coeff_isneg(S(coeff)):                     s = prettyForm(*stringPict.next(s, ' '))                     pform = self._print(item)                 else:

Error pretty printing MatAdd The code shouldn't be using sympify to handle string arguments from MatrixSymbol. I don't even understand what the code is doing. Why does it omit the when the first argument is negative? This seems to assume that the arguments of MatAdd have a certain form, and that they will always print a certain way if they are negative.


Question: return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args)  <ins>    def _print_Rational(self, e):        return '{0}({1})/{0}({2})'.format(            self._module_format('mpmath.mpf'),            e.p,            e.q,            )</ins>     def _print_uppergamma(self, e):         return "{0}({1}, {2}, {3})".format(             self._module_format('mpmath.gammainc'),

lambdify(modules='mpmath') doesn't wrap rationals This results in reduced precision results from , because the 232/3 isn't evaluated at full precision. Originally reported at


Question: return isinstance(ident, str) and cls._safe_ident_re.match(ident) \                 and not (keyword.iskeyword(ident) or ident == 'None')      def _preprocess(self, args, expr):         """Preprocess args, expr to replace arguments that do not map         to valid Python identifiers.          Returns string form of args, and updated expr.         """        from sympy import Dummy, Symbol, Function, flatten        from sympy import Dummy, Symbol, MatrixSymbol, Function, flatten         from sympy.matrices import DeferredVector          dummify = self._dummify

lambdify does not work with certain MatrixSymbol names even with dummify=True is happy with curly braces in a symbol name and with s, but not with both at the same time, even if is . Here is some basic code that gives the error. The following two lines of code work: The following two lines of code give a :


Question: argstrs.append(nested_argstrs)             elif isinstance(arg, DeferredVector):                 argstrs.append(str(arg))            elif isinstance(arg, Symbol):            elif isinstance(arg, Symbol) or isinstance(arg, MatrixSymbol):                 argrep = self._argrepr(arg)                  if dummify or not self._is_safe_ident(argrep):


Question: argstrs.append(self._argrepr(dummy))                 expr = self._subexpr(expr, {arg: dummy})             else:                argstrs.append(str(arg))                argrep = self._argrepr(arg)                if dummify:                    dummy = Dummy()                    argstrs.append(self._argrepr(dummy))                    expr = self._subexpr(expr, {arg: dummy})                else:                    argstrs.append(str(arg))          return argstrs, expr


Question: self._shape = shape         self._array = list(flat_list)         self._rank = len(shape)        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0        self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1)         return self      def __setitem__(self, index, value):

of rank-0 arrays returns 0 always returns zero for rank-0 arrays (scalars). I believe the correct value should be one, which is the number of elements of the iterator and the observed behaviour in numpy. In numpy we have the following: This was tested in sympy 1.2-rc1 running in Python 3.6.6 of rank-0 arrays returns 0 always returns zero for rank-0 arrays (scalars). I believe the correct value should be one, which is the number of elements of the iterator and the observed behaviour in numpy. In numpy we have the following: This was tested in sympy 1.2-rc1 running in Python 3.6.6


Question: 'precision': 17,         'user_functions': {},         'human': True,        'allow_unknown_functions': True,         'contract': True,         'dereference': set(),         'error_on_reserved': False,diff --git a/sympy/printing/codeprinter.py b/sympy/printing/codeprinter.py-- a/sympy/printing/codeprinter.py++ b/sympy/printing/codeprinter.py

[regression] lambdify with Matrix: I'm trying to create a lambda function from a sympy expression that involves a dot product with a . Since at least sympy 1.2, this fails. MWE: Error message:


Question: 'error_on_reserved': False,         'reserved_word_suffix': '_',         'human': True,        'inline': False        'inline': False,        'allow_unknown_functions': True,     }      def __init__(self, settings=None):


Question: elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):             # inlined function             return self._print(expr._imp_(*expr.args))        elif expr.is_Function and self._settings.get('allow_unknown_functions', True):            return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args)))         else:             return self._print_not_supported(expr) diff --git a/sympy/printing/fcode.py b/sympy/printing/fcode.py-- a/sympy/printing/fcode.py++ b/sympy/printing/fcode.py


Question: 'precision': 17,         'user_functions': {},         'human': True,        'allow_unknown_functions': True,         'source_format': 'fixed',         'contract': True,         'standard': 77,diff --git a/sympy/printing/glsl.py b/sympy/printing/glsl.py-- a/sympy/printing/glsl.py++ b/sympy/printing/glsl.py


Question: 'precision': 9,         'user_functions': {},         'human': True,        'allow_unknown_functions': True,         'contract': True,         'error_on_reserved': False,         'reserved_word_suffix': '_'diff --git a/sympy/printing/jscode.py b/sympy/printing/jscode.py-- a/sympy/printing/jscode.py++ b/sympy/printing/jscode.py


Question: 'precision': 17,         'user_functions': {},         'human': True,        'allow_unknown_functions': True,         'contract': True     } diff --git a/sympy/printing/julia.py b/sympy/printing/julia.py-- a/sympy/printing/julia.py++ b/sympy/printing/julia.py


Question: 'precision': 17,         'user_functions': {},         'human': True,        'allow_unknown_functions': True,         'contract': True,         'inline': True,     }diff --git a/sympy/printing/mathematica.py b/sympy/printing/mathematica.py-- a/sympy/printing/mathematica.py++ b/sympy/printing/mathematica.py


Question: 'precision': 15,         'user_functions': {},         'human': True,        'allow_unknown_functions': True,     }      _number_symbols = set()diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py-- a/sympy/printing/octave.py++ b/sympy/printing/octave.py


Question: 'precision': 17,         'user_functions': {},         'human': True,<ins>        'allow_unknown_functions': True,</ins>         'contract': True,         'inline': True,     }


Question: return outstr      def _print_Indexed(self, expr):        tex = self._print(expr.base)+'_{%s}' % ','.join(        tex_base = self._print(expr.base)        tex = '{'+tex_base+'}'+'_{%s}' % ','.join(             map(self._print, expr.indices))         return tex

not pretty printing indexed(x1, i) not sure if this is expected behavior but i'm expecting x_{1,i} !


Question: # of times it appeared as a Not(symbol),     # of times it appeared as a Symbol in an And or Or,     # of times it appeared as a Not(Symbol) in an And or Or,    sum of the number of arguments with which it appeared,    counting Symbol as 1 and Not(Symbol) as 2    sum of the number of arguments with which it appeared    as a Symbol, counting Symbol as 1 and Not(Symbol) as 2    and counting self as 1     ]      >>> from sympy.logic.boolalg import _finger as finger

xor boolmap equivalent to xnor? - Flaw in finger fingerprint results in The simplified functions fro f1 and f2 are correct, and clearly different, yet bool_map returned what it though to be a valid symbol mapping?


Question: >>> from sympy.abc import a, b, x, y     >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y))     >>> dict(finger(eq))    {(0, 0, 1, 0, 2): [x], (0, 0, 1, 0, 3): [a, b], (0, 0, 1, 2, 8): [y]}    {(0, 0, 1, 0, 2): [x], (0, 0, 1, 0, 3): [a, b], (0, 0, 1, 2, 2): [y]}    >>> dict(finger(x & ~y))    {(0, 1, 0, 0, 0): [y], (1, 0, 0, 0, 0): [x]}    The equation must not have more than one level of nesting:    >>> dict(finger(And(Or(x, y), y)))    {(0, 0, 1, 0, 2): [x], (1, 0, 1, 0, 2): [y]}    >>> dict(finger(And(Or(x, And(a, x)), y)))    Traceback (most recent call last):    ...    NotImplementedError: unexpected level of nesting      So y and x have unique fingerprints, but a and b do not.     """


Question: if ai.is_Symbol:                     d[ai][2] += 1                     d[ai][-1] += o                else:                elif ai.is_Not:                     d[ai.args[0]][3] += 1                    d[ai.args[0]][-1] += o                else:                    raise NotImplementedError('unexpected level of nesting')     inv = defaultdict(list)     for k, v in ordered(iter(d.items())):         inv[tuple(v)].append(k)


Question: # do some quick checks         if function1.__class__ != function2.__class__:            return None            return None  # maybe simplification would make them the same         if len(function1.args) != len(function2.args):            return None            return None  # maybe simplification would make them the same         if function1.is_Symbol:             return {function1: function2}


Question: m = match(a, b)     if m:         return a, m    return m is not None    return m


Question: "Abs": "abs",     "conjugate": "conjg",     "Max": "max",    "Min": "min"    "Min": "min", }

autowrap fortran fails with expression containing Mod function twice Minimal example: Error: And here's the generated code. Clearly the problem is that Mod gets imported twice. Hopefully this is an easy fix but I don't know where to start.


Question: else:             return CodePrinter._print_Function(self, expr.func(*args))     def _print_Mod(self, expr):        # NOTE : Fortran has the functions mod() and modulo(). modulo() behaves        # the same wrt to the sign of the arguments as Python and SymPy's        # modulus computations (% and Mod()) but is not available in Fortran 66        # or Fortran 77, thus we raise an error.        if self._settings['standard'] in [66, 77]:            msg = ("Python % operator and SymPy's Mod() function are not "                   "supported by Fortran 66 or 77 standards.")            raise NotImplementedError(msg)        else:            x, y = expr.args            return "      modulo({}, {})".format(self._print(x), self._print(y))     def _print_ImaginaryUnit(self, expr):         # purpose: print complex numbers nicely in Fortran.         return "cmplx(0,1)"diff --git a/sympy/utilities/codegen.py b/sympy/utilities/codegen.py-- a/sympy/utilities/codegen.py++ b/sympy/utilities/codegen.py


Question: assign_to = result.result_var              constants, not_fortran, f_expr = self._printer_method_with_settings(                'doprint', dict(human=False, source_format='free'),                'doprint', dict(human=False, source_format='free', standard=95),                 result.expr, assign_to=assign_to)              for obj, v in sorted(constants, key=str):


Question: if a.is_Symbol:                 nc_syms.add(a)             elif not (a.is_Add or a.is_Mul or a.is_Pow):                if all(s.is_commutative for s in a.free_symbols):                    rep.append((a, Dummy()))                else:                    nc_obj.add(a)                nc_obj.add(a)                 pot.skip()      # If there is only one nc symbol or object, it can be factored regularly

factor() function issue for non-commutative objects In commit by from line 652 to line 660 in the file , there are some parts that I couldn't understand: I am trying to add a non-commutative class whose freesymbols are commutative. (e.g., operator with time dependence) In this case, even if the object itself is non-commutative, the factor() function gives the wrong result, because of the lines In my understanding, this line treats a non-commutative object as commutative if all its freesymbols are commutative. What is the purpose of this line?


Question: return [i[0] if i[1] == 1 else i for i in v]      @classmethod    def _sort_variable_count(cls, varcounts):    def _sort_variable_count(cls, vc):         """        Sort (variable, count) pairs by variable, but disallow sorting of non-symbols.        Sort (variable, count) pairs into canonical order while        retaining order of variables that do not commute during        differentiation:         The count is not sorted. It is kept in the same order as the input        after sorting by variable.        When taking derivatives, the following rules usually hold:        * Derivative wrt different symbols commute.        * Derivative wrt different non-symbols commute.        * Derivatives wrt symbols and non-symbols don't commute.        * symbols and functions commute with each other        * derivatives commute with each other        * a derivative doesn't commute with anything it contains        * any other object is not allowed to commute if it has          free symbols in common with another object          Examples         ========         >>> from sympy import Derivative, Function, symbols        >>> from sympy import Derivative, Function, symbols, cos         >>> vsort = Derivative._sort_variable_count         >>> x, y, z = symbols('x y z')         >>> f, g, h = symbols('f g h', cls=Function)         >>> vsort([(x, 3), (y, 2), (z, 1)])        [(x, 3), (y, 2), (z, 1)]        >>> vsort([(h(x), 1), (g(x), 1), (f(x), 1)])        [(f(x), 1), (g(x), 1), (h(x), 1)]        Contiguous items are collapsed into one pair:         >>> vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1), (f(x), 1)])        [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)]        >>> vsort([(x, 1), (x, 1)])        [(x, 2)]        >>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)])        [(y, 2), (f(x), 2)]         >>> vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)])        [(x, 1), (f(x), 1), (y, 1), (f(y), 1)]        Ordering is canonical.         >>> vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1), (h(x), 1), (y, 2), (x, 1)])        [(x, 2), (y, 1), (f(x), 1), (g(x), 1), (z, 1), (h(x), 1), (x, 1), (y, 2)]        >>> def vsort0(*v):        ...     # docstring helper to        ...     # change vi -> (vi, 0), sort, and return vi vals        ...     return [i[0] for i in vsort([(i, 0) for i in v])]         >>> vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1), (g(x), 1)])        [(y, 1), (z, 1), (f(x), 1), (x, 1), (f(x), 1), (g(x), 1)]        >>> vsort0(y, x)        [x, y]        >>> vsort0(g(y), g(x), f(y))        [f(y), g(x), g(y)]         >>> vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)])        [(y, 2), (z, 1), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1), (x, 1), (y, 1), (z, 2), (z, 1)]        Symbols are sorted as far to the left as possible but never        move to the left of a derivative having the same symbol in        its variables; the same applies to AppliedUndef which are        always sorted after Symbols:         >>> dfx = f(x).diff(x)        >>> assert vsort0(dfx, y) == [y, dfx]        >>> assert vsort0(dfx, x) == [dfx, x]         """        sorted_vars = []        symbol_part = []        non_symbol_part = []        for (v, c) in varcounts:            if not v.is_symbol:                if len(symbol_part) > 0:                    sorted_vars.extend(sorted(symbol_part,                                              key=lambda i: default_sort_key(i[0])))                    symbol_part = []                non_symbol_part.append((v, c))        from sympy.utilities.iterables import uniq, topological_sort        if not vc:            return []        vc = list(vc)        if len(vc) == 1:            return [Tuple(*vc[0])]        V = list(range(len(vc)))        E = []        v = lambda i: vc[i][0]        D = Dummy()        def _block(d, v, wrt=False):            # return True if v should not come before d else False            if d == v:                return wrt            if d.is_Symbol:                return False            if isinstance(d, Derivative):                # a derivative blocks if any of it's variables contain                # v; the wrt flag will return True for an exact match                # and will cause an AppliedUndef to block if v is in                # the arguments                if any(_block(k, v, wrt=True)                        for k, _ in d.variable_count):                    return True                return False            if not wrt and isinstance(d, AppliedUndef):                return False            if v.is_Symbol:                return v in d.free_symbols            if isinstance(v, AppliedUndef):                return _block(d.xreplace({v: D}), D)            return d.free_symbols & v.free_symbols        for i in range(len(vc)):            for j in range(i):                if _block(v(j), v(i)):                    E.append((j,i))        # this is the default ordering to use in case of ties        O = dict(zip(ordered(uniq([i for i, c in vc])), range(len(vc))))        ix = topological_sort((V, E), key=lambda i: O[v(i)])        # merge counts of contiguously identical items        merged = []        for v, c in [vc[i] for i in ix]:            if merged and merged[-1][0] == v:                merged[-1][1] += c             else:                if len(non_symbol_part) > 0:                    sorted_vars.extend(sorted(non_symbol_part,                                              key=lambda i: default_sort_key(i[0])))                    non_symbol_part = []                symbol_part.append((v, c))        if len(non_symbol_part) > 0:            sorted_vars.extend(sorted(non_symbol_part,                                      key=lambda i: default_sort_key(i[0])))        if len(symbol_part) > 0:            sorted_vars.extend(sorted(symbol_part,                                      key=lambda i: default_sort_key(i[0])))        return [Tuple(*i) for i in sorted_vars]                merged.append([v, c])        return [Tuple(*i) for i in merged]      def _eval_is_commutative(self):         return self.expr.is_commutative

better canonicalization of variables of Derivative Better canonicalization of will be had if any symbols, appearing after functions, that are not in the free symbols of the function, appear before the functions: should equal .


Question: return fuzzy_bool(test.is_positive)     def equation(self, x='x', y='y'):        """The equation of the ellipse.    def equation(self, x='x', y='y', _slope=None):        """        Returns the equation of an ellipse aligned with the x and y axes;        when slope is given, the equation returned corresponds to an ellipse        with a major axis having that slope.          Parameters         ==========

recognize elliptical integrals Original issue for : Original author: Added function for finding equation of Ellipse using slope as parameter and faster method for calculation of circumference of ellipse Added function for finding equation of Ellipse using slope as parameter. Added another method for calculation of circumference of ellipse. Added a new method called Pluralized the following methods -- This PR uses the approach to finding equation of ellipse using slope, length of semi minor axis and length of semi major axis as inputs given This could be an functionality to the equation finding method in class . Thanks to for providing the approach. Please take a look at this PR and suggest changes. I will be glad to implement them. Thanks. <!-- BEGIN RELEASE NOTES --geometry function for finding equation of Ellipse using slope as parameter <!-- END RELEASE NOTES --


Question: Label for the x-axis. Default value is 'x'.         y : str, optional             Label for the y-axis. Default value is 'y'.<ins>        _slope : Expr, optional                The slope of the major axis. Ignored when 'None'.</ins>          Returns         =======


Question: Examples         ========         >>> from sympy import Point, Ellipse        >>> from sympy import Point, Ellipse, pi        >>> from sympy.abc import x, y         >>> e1 = Ellipse(Point(1, 0), 3, 2)        >>> e1.equation()        >>> eq1 = e1.equation(x, y); eq1         y**2/4 + (x/3 - 1/3)**2 - 1        >>> eq2 = e1.equation(x, y, _slope=1); eq2        (-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1        A point on e1 satisfies eq1. Let's use one on the x-axis:        >>> p1 = e1.center + Point(e1.major, 0)        >>> assert eq1.subs(x, p1.x).subs(y, p1.y) == 0        When rotated the same as the rotated ellipse, about the center        point of the ellipse, it will satisfy the rotated ellipse's        equation, too:        >>> r1 = p1.rotate(pi/4, e1.center)        >>> assert eq2.subs(x, r1.x).subs(y, r1.y) == 0        References        ==========        .. [1] https://math.stackexchange.com/questions/108270/what-is-the-equation-of-an-ellipse-that-is-not-aligned-with-the-axis        .. [2] https://en.wikipedia.org/wiki/Ellipse#Equation_of_a_shifted_ellipse          """         x = _symbol(x, real=True)         y = _symbol(y, real=True)        t1 = ((x - self.center.x) / self.hradius)**2        t2 = ((y - self.center.y) / self.vradius)**2        return t1 + t2 - 1        dx = x - self.center.x        dy = y - self.center.y        if _slope is not None:            L = (dy - _slope*dx)**2            l = (_slope*dy + dx)**2            h = 1 + _slope**2            b = h*self.major**2            a = h*self.minor**2            return l/b + L/a - 1        else:            t1 = (dx/self.hradius)**2            t2 = (dy/self.vradius)**2            return t1 + t2 - 1      def evolute(self, x='x', y='y'):         """The equation of evolute of the ellipse.


Question: from sympy.core import S, Symbol, diff, symbols from sympy.solvers import linsolve from sympy.printing import sstrfrom sympy.functions import SingularityFunction, Piecewisefrom sympy.functions import SingularityFunction, Piecewise, factorial from sympy.core import sympify from sympy.integrals import integrate from sympy.series import limit

Problem with Beam module I think there is a problem with the Beam module when using a force with an order bigger than 1. This is an example where R should be 1/3 and remains constant when changing the length of the beam, but unfortunately it's not the case. I believe it has to do with the formation of the load equation, where the higher order compensation isn't been taken into consideration. !


Question: point forces this is the location of application.         order : Integer             The order of the applied load.            - For moments, order= -2            - For point loads, order=-1            - For constant distributed load, order=0            - For ramp loads, order=1            - For parabolic ramp loads, order=2            - ... so on.               - For moments, order = -2               - For point loads, order =-1               - For constant distributed load, order = 0               - For ramp loads, order = 1               - For parabolic ramp loads, order = 2               - ... so on.         end : Sympifyable, optional             An optional argument that can be used if the load has an end point             within the length of the beam.


Question: ========         There is a beam of length 4 meters. A moment of magnitude 3 Nm is         applied in the clockwise direction at the starting point of the beam.        A pointload of magnitude 4 N is applied from the top of the beam at        A point load of magnitude 4 N is applied from the top of the beam at         2 meters from the starting point and a parabolic ramp load of magnitude         2 N/m is applied below the beam starting from 2 meters to 3 meters         away from the starting point of the beam.


Question: >>> b = Beam(4, E, I)         >>> b.apply_load(-3, 0, -2)         >>> b.apply_load(4, 2, -1)        >>> b.apply_load(-2, 2, 2, end = 3)        >>> b.apply_load(-2, 2, 2, end=3)         >>> b.load        -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2)            + 2*SingularityFunction(x, 3, 0) + 2*SingularityFunction(x, 3, 2)        -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)         """         x = self.variable         value = sympify(value)


Question: self._load += value*SingularityFunction(x, start, order)          if end:            if order == 0:                self._load -= value*SingularityFunction(x, end, order)            elif order.is_positive:                self._load -= value*SingularityFunction(x, end, order) + value*SingularityFunction(x, end, 0)            else:                raise ValueError("""Order of the load should be positive.""")            if order.is_negative:                msg = ("If 'end' is provided the 'order' of the load cannot "                       "be negative, i.e. 'end' is only valid for distributed "                       "loads.")                raise ValueError(msg)            # NOTE : A Taylor series can be used to define the summation of            # singularity functions that subtract from the load past the end            # point such that it evaluates to zero past 'end'.            f = value * x**order            for i in range(0, order + 1):                self._load -= (f.diff(x, i).subs(x, end - start) *                               SingularityFunction(x, end, i) / factorial(i))      def remove_load(self, value, start, order, end=None):         """


Question: >>> b = Beam(4, E, I)         >>> b.apply_load(-3, 0, -2)         >>> b.apply_load(4, 2, -1)        >>> b.apply_load(-2, 2, 2, end = 3)        >>> b.apply_load(-2, 2, 2, end=3)         >>> b.load        -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2)            + 2*SingularityFunction(x, 3, 0) + 2*SingularityFunction(x, 3, 2)        -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)         >>> b.remove_load(-2, 2, 2, end = 3)         >>> b.load         -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)


Question: self._load -= value*SingularityFunction(x, start, order)             self._applied_loads.remove((value, start, order, end))         else:            raise ValueError("""No such load distribution exists on the beam object.""")            msg = "No such load distribution exists on the beam object."            raise ValueError(msg)          if end:            if order == 0:                self._load += value*SingularityFunction(x, end, order)            elif order.is_positive:                self._load += value*SingularityFunction(x, end, order) + value*SingularityFunction(x, end, 0)            else:                raise ValueError("""Order of the load should be positive.""")            # TODO : This is essentially duplicate code wrt to apply_load,            # would be better to move it to one location and both methods use            # it.            if order.is_negative:                msg = ("If 'end' is provided the 'order' of the load cannot "                       "be negative, i.e. 'end' is only valid for distributed "                       "loads.")                raise ValueError(msg)            # NOTE : A Taylor series can be used to define the summation of            # singularity functions that subtract from the load past the end            # point such that it evaluates to zero past 'end'.            f = value * x**order            for i in range(0, order + 1):                self._load += (f.diff(x, i).subs(x, end - start) *                               SingularityFunction(x, end, i) / factorial(i))      @property     def load(self):


Question: ========         There is a beam of length 4 meters. A moment of magnitude 3 Nm is         applied in the clockwise direction at the starting point of the beam.        A pointload of magnitude 4 N is applied from the top of the beam at        A point load of magnitude 4 N is applied from the top of the beam at         2 meters from the starting point and a parabolic ramp load of magnitude         2 N/m is applied below the beam starting from 3 meters away from the         starting point of the beam.


Question: else:             return expr <ins>    def _print_Basic(self, expr):        l = [self._print(o) for o in expr.args]        return self._deal_with_super_sub(expr.__class__.__name__) + r"\left(%s\right)" % ", ".join(l)</ins>     def _print_bool(self, e):         return r"\mathrm{%s}" % e

LaTeX printing for Matrix Expression The bad part is not only is Trace not recognized, but whatever printer is being used doesn't fallback to the LaTeX printer for the inner expression (it should be ).


Question: else:             return "%s^T" % self._print(mat) <ins>    def _print_Trace(self, expr):        mat = expr.arg        return r"\mathrm{tr}\left (%s \right )" % self._print(mat)</ins>     def _print_Adjoint(self, expr):         mat = expr.arg         from sympy.matrices import MatrixSymbol


Question: Roots of a univariate polynomial separated into disjoint     real or complex intervals and indexed in a fixed order.     Currently only rational coefficients are allowed.    Can be imported as ``CRootOf``.    Can be imported as ``CRootOf``. To avoid confusion, the    generator must be a Symbol.       Examples

RootOf might ignore generator This is related to but a little different. I'm not sure of all the ramifications but just want to document this. Note how feeding RootOf an expression in terms of a new generator might ignore that generator if the form of the polynomial is the same


Question: >>> t.eval_rational(n=2)     104755/2097152 - 6634255*I/2097152 <ins>    Notes    =====    Although a PurePoly can be constructed from a non-symbol generator    RootOf instances of non-symbols are disallowed to avoid confusion    over what root is being represented.    >>> from sympy import exp, PurePoly    >>> PurePoly(x) == PurePoly(exp(x))    True    >>> CRootOf(x - 1, 0)    1    >>> CRootOf(exp(x) - 1, 0)  # would correspond to x == 0    Traceback (most recent call last):    ...    sympy.polys.polyerrors.PolynomialError: generator must be a Symbol</ins>     See Also     ========     eval_approx


Question: if not poly.is_univariate:             raise PolynomialError("only univariate polynomials are allowed") <ins>        if not poly.gen.is_Symbol:            # PurePoly(sin(x) + 1) == PurePoly(x + 1) but the roots of            # x for each are not the same: issue 8617            raise PolynomialError("generator must be a Symbol")</ins>         degree = poly.degree()          if degree <= 0:


Question: "asech": [(lambda x: True, "ArcSech")],     "acsch": [(lambda x: True, "ArcCsch")],     "conjugate": [(lambda x: True, "Conjugate")],    "Max": [(lambda *x: True, "Max")],    "Min": [(lambda *x: True, "Min")], }

mathematica_code gives wrong output with Max If I run the code then I would expect the output which is valid Mathematica code but instead I get which is not valid Mathematica code.


Question: return "%s[%s]" % (mfunc, self.stringify(expr.args, ", "))         return expr.func.__name__ + "[%s]" % self.stringify(expr.args, ", ") <ins>    _print_MinMaxBase = _print_Function</ins>     def _print_Integral(self, expr):         if len(expr.variables) == 1 and not expr.limits[0][1:]:             args = [expr.args[0], expr.variables[0]]


Question: lambda x: _eapply(factor, x, trigs),         TR14,  # factored powers of identities         [identity, lambda x: _eapply(_mexpand, x, trigs)],        TRmorrie,         TR10i,  # sin-cos products > sin-cos of sums        TRmorrie,         [identity, TR8],  # sin-cos products -> sin-cos of sums         [identity, lambda x: TR2i(TR2(x))],  # tan -> sin-cos -> tan         [

can't simplify sin/cos with Rational? latest cloned sympy, python 3 on windows firstly, cos, sin with symbols can be simplified; rational number can be simplified says but says


Question: m10 = 2*s*(q.b*q.c + q.d*q.a)         m11 = 1 - 2*s*(q.b**2 + q.d**2)        m12 = 2*s*(q.c*q.d + q.b*q.a)        m12 = 2*s*(q.c*q.d - q.b*q.a)          m20 = 2*s*(q.b*q.d - q.c*q.a)         m21 = 2*s*(q.c*q.d + q.b*q.a)

Incorrect result with Quaterniont.torotationmatrix() There appears to be an error in the output. The simplest example I created to illustrate the problem is as follows: One of the functions should be negative. What was the reference of the original equations?


Question: >>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1     False     For matrix expressions:    >>> from sympy import MatrixSymbol, sqrt    >>> A = MatrixSymbol("A", 3, 3)    >>> _coeff_isneg(-sqrt(2)*A)    True    >>> _coeff_isneg(sqrt(2)*A)    False     """     if a.is_MatMul:        a = a.args[0]     if a.is_Mul:         a = a.args[0]     return a.is_Number and a.is_negativediff --git a/sympy/matrices/expressions/blockmatrix.py b/sympy/matrices/expressions/blockmatrix.py-- a/sympy/matrices/expressions/blockmatrix.py++ b/sympy/matrices/expressions/blockmatrix.py

LaTeX printer omits necessary parentheses in matrix products such as x(-y) The product of x and -y, where x, y are MatrixSymbols, is printed as by the LaTeX printer: Source: on Stack Overflow.


Question: Matrix([[I, Z]])      >>> print(block_collapse(C*B))    Matrix([[X, Z*Y + Z]])    Matrix([[X, Z + Z*Y]])      """     def __new__(cls, *args):


Question: Matrix([[I, Z]])      >>> print(block_collapse(C*B))    Matrix([[X, Z*Y + Z]])    Matrix([[X, Z + Z*Y]])     """     hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix)     rule = exhaust(diff --git a/sympy/matrices/expressions/matexpr.py b/sympy/matrices/expressions/matexpr.py-- a/sympy/matrices/expressions/matexpr.py++ b/sympy/matrices/expressions/matexpr.py


Question: >>> A.shape     (3, 4)     >>> 2*A*B + Identity(3)    2*A*B + I    I + 2*A*B     """     is_commutative = False     is_symbol = 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_NoneType(self, e):         return r"\mathrm{%s}" % e <del></del>     def _print_Add(self, expr, order=None):         if self.order == 'none':             terms = list(expr.args)


Question: else:             return r"%s^\dagger" % self._print(mat)     def _print_MatAdd(self, expr):        terms = [self._print(t) for t in expr.args]        l = []        for t in terms:            if t.startswith('-'):                sign = "-"                t = t[1:]            else:                sign = "+"            l.extend([sign, t])        sign = l.pop(0)        if sign == '+':            sign = ""        return sign + ' '.join(l)     def _print_MatMul(self, expr):         from sympy import Add, MatAdd, HadamardProduct, MatMul, Mul         def parens(x):            if isinstance(x, (Add, MatAdd, HadamardProduct)):                return r"\left(%s\right)" % self._print(x)            return self._print(x)        parens = lambda x: self.parenthesize(x, precedence_traditional(expr), False)         if isinstance(expr, MatMul) and expr.args[0].is_Number and expr.args[0]<0:            expr = Mul(-1*expr.args[0], MatMul(*expr.args[1:]))            return '-' + ' '.join(map(parens, expr.args))        args = expr.args        if isinstance(args[0], Mul):            args = args[0].as_ordered_factors() + list(args[1:])        else:            args = list(args)        if isinstance(expr, MatMul) and _coeff_isneg(expr):            if args[0] == -1:                args = args[1:]            else:                args[0] = -args[0]            return '- ' + ' '.join(map(parens, args))         else:            return ' '.join(map(parens, expr.args))            return ' '.join(map(parens, args))      def _print_Mod(self, expr, exp=None):         if exp is not None:diff --git a/sympy/printing/precedence.py b/sympy/printing/precedence.py-- a/sympy/printing/precedence.py++ b/sympy/printing/precedence.py


Question: "Function" : PRECEDENCE["Func"],     "NegativeInfinity": PRECEDENCE["Add"],     "MatAdd": PRECEDENCE["Add"],    "MatMul": PRECEDENCE["Mul"],     "MatPow": PRECEDENCE["Pow"],     "TensAdd": PRECEDENCE["Add"],    # As soon as `TensMul` is a subclass of `Mul`, remove this:     "TensMul": PRECEDENCE["Mul"],     "HadamardProduct": PRECEDENCE["Mul"],     "KroneckerProduct": PRECEDENCE["Mul"],diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


Question: return '.*'.join([self.parenthesize(arg, precedence(expr))             for arg in expr.args]) <del>    def _print_MatAdd(self, expr):        terms = [self.parenthesize(arg, precedence(expr))             for arg in expr.args]        l = []        for t in terms:            if t.startswith('-'):                sign = "-"                t = t[1:]            else:                sign = "+"            l.extend([sign, t])        sign = l.pop(0)        if sign == '+':            sign = ""        return sign + ' '.join(l)</del>     def _print_NaN(self, expr):         return 'nan'


Question: from __future__ import print_function, division  from tokenize import (generate_tokens, untokenize, TokenError,    NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN)    NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE)  from keyword import iskeyword

Python 3.7 test failures Running tests from master under Python 3.7.1 (which isn't tested on Travis) I see some failures. The fastest ones to see are from but there is another in . I'm not sure what has changed in 3.7 to cause this. The error from is


Question: # work with function exponentiation     for tok, nextTok in zip(tokens, tokens[1:]):         result.append(tok)        if (tok[0] == NAME and              nextTok[0] != OP and              nextTok[0] != ENDMARKER):        if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]):             if _token_callable(tok, local_dict, global_dict, nextTok):                 result.append((OP, '('))                 appendParen += 1


Question: flag = False     toknum, tokval = tokens[0]     tokLen = len(tokens)     if toknum == NAME and tokval == 'lambda':        if tokLen == 2:        if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE:            # In Python 3.6.7+, inputs without a newline get NEWLINE added to            # the tokens             result.extend(tokens)         elif tokLen > 2:             result.extend([


Question: points = list(uniq(points))         return Point.affine_rank(*points) <= 2     def distance(self, p):        """The Euclidean distance from self to point p.        Parameters        ==========        p : Point    def distance(self, other):        """The Euclidean distance between self and another GeometricEntity.          Returns         =======          distance : number or symbolic expression.         Raises        ======        AttributeError : if other is a GeometricEntity for which                         distance is not defined.        TypeError : if other is not recognized as a GeometricEntity.         See Also         ========

Should Point.distance(Line) return distance? In Geometry module, can be used to compute distance, but cannot. Should this be made symmetric?


Question: Examples         ========         >>> from sympy.geometry import Point        >>> from sympy.geometry import Point, Line         >>> p1, p2 = Point(1, 1), Point(4, 5)        >>> l = Line((3, 1), (2, 2))         >>> p1.distance(p2)         5        >>> p1.distance(l)        sqrt(2)        The computed distance may be symbolic, too:          >>> from sympy.abc import x, y         >>> p3 = Point(x, y)        >>> p3.distance(Point(0, 0))        >>> p3.distance((0, 0))         sqrt(x**2 + y**2)          """        s, p = Point._normalize_dimension(self, Point(p))        return sqrt(Add(*((a - b)**2 for a, b in zip(s, p))))        if not isinstance(other , GeometryEntity) :            try :                other = Point(other, dim=self.ambient_dimension)            except TypeError :                raise TypeError("not recognized as a GeometricEntity: %s" % type(other))        if isinstance(other , Point) :            s, p = Point._normalize_dimension(self, Point(other))            return sqrt(Add(*((a - b)**2 for a, b in zip(s, p))))        try :            return other.distance(self)        except AttributeError :            raise AttributeError("distance between Point and %s is not defined" % type(other))      def dot(self, p):         """Return dot product of self with another Point."""


Question: return Tuple(*divmod(self.p, other.p))         else:             rat = self/other        w = sign(rat)*int(abs(rat))  # = rat.floor()        w = int(rat) if rat > 0 else int(rat) - 1         r = self - other*w         return Tuple(w, r)

SymPy's doesn't agree with the builtin divmod Both are mathematically correct according to the invariant in the docstring, , but we should be consistent with Python. In general in Python, the sign of mod should be the same as the sign of the second argument. Our is already correct, so it's just that needs to be corrected


Question: >>> A = MatrixSymbol('A', 3, 3)     >>> B = MatrixSymbol('B', 3, 3)     >>> Inverse(A)    A^-1    A**(-1)     >>> A.inverse() == Inverse(A)     True     >>> (A*B).inverse()    B^-1*A^-1    B**(-1)*A**(-1)     >>> Inverse(A*B)    (A*B)^-1    (A*B)**(-1)      """     is_Inverse = True

Can't get an inverted float matrix with sympy and numpy Trying to get an inverted matrix with sympy and numpy. lambify fails with the following message:


Question: >>> from sympy import MatrixSymbol, Q, assuming, refine     >>> X = MatrixSymbol('X', 2, 2)     >>> X.I    X^-1    X**(-1)     >>> with assuming(Q.orthogonal(X)):     ...     print(refine(X.I))     X.Tdiff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py-- a/sympy/printing/pycode.py++ b/sympy/printing/pycode.py


Question: "Matrix multiplication printer"         return '({0})'.format(').dot('.join(self._print(i) for i in expr.args))     def _print_MatPow(self, expr):        "Matrix power printer"        return '{0}({1}, {2})'.format(self._module_format('numpy.linalg.matrix_power'),            self._print(expr.args[0]), self._print(expr.args[1]))    def _print_Inverse(self, expr):        "Matrix inverse printer"        return '{0}({1})'.format(self._module_format('numpy.linalg.inv'),            self._print(expr.args[0]))     def _print_DotProduct(self, expr):         # DotProduct allows any shape order, but numpy.dot does matrix         # multiplication, so we have to make sure it gets 1 x n by n x 1.diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


Question: self._print(i.max))      def _print_Inverse(self, I):        return "%s^-1" % self.parenthesize(I.arg, PRECEDENCE["Pow"])        return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"])      def _print_Lambda(self, obj):         args, expr = obj.argsdiff --git a/sympy/utilities/lambdify.py b/sympy/utilities/lambdify.py-- a/sympy/utilities/lambdify.py++ b/sympy/utilities/lambdify.py


Question: MODULES = {     "math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)),     "mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)),    "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *",)),    "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)),     "scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import numpy; import scipy; from scipy import *; from scipy.special import *",)),     "tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import_module('tensorflow')",)),     "sympy": (SYMPY, SYMPY_DEFAULT, {}, (


Question: elif isinstance(a, TrigonometricFunction):             period = periodicity(a, symbol)         #check if 'f' is linear in 'symbol'        elif degree(a, symbol) == 1 and symbol not in n.free_symbols:            period = Abs(n / a.diff(symbol))        elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and            symbol not in n.free_symbols):                period = Abs(n / a.diff(symbol))      elif period is None:         from sympy.solvers.decompogen import compogendiff --git a/sympy/polys/polytools.py b/sympy/polys/polytools.py-- a/sympy/polys/polytools.py++ b/sympy/polys/polytools.py

The behavior of degree(f, x) on rational functions I wanted to know if SymPy can compute degrees of rational functions, so I tried Perhaps the degree of a rational function is not implemented, but if so, should this fail instead?


Question: """      f = sympify(f, strict=True)    gen_is_Num = sympify(gen, strict=True).is_Number     if f.is_Poly:         p = f         isNum = p.as_expr().is_Number     else:         isNum = f.is_Number         if not isNum:            p, _ = poly_from_expr(f)            if gen_is_Num:                p, _ = poly_from_expr(f)            else:                p, _ = poly_from_expr(f, gen)      if isNum:         return S.Zero if f else S.NegativeInfinity     if not sympify(gen, strict=True).is_Number:    if not gen_is_Num:         if f.is_Poly and gen not in p.gens:             # try recast without explicit gens             p, _ = poly_from_expr(f.as_expr())


Question: from __future__ import print_function, division from sympy.core.numbers import nanfrom sympy.core.numbers import nan, Integerfrom sympy.core.compatibility import integer_types from .function import Function

Mod(3i, 2) unchanged should reduce to (as reported in ) and will do so with a change something like this: Returns correct result to Mod(3i, 2). modified the to return correct answer to Mod(3i, 2). a test (All as suggested by ) Earlier sympify(3k%2) Mod(3k,2) Now sympify(3k%2) Mod(k,2) Release Notes <!-- BEGIN RELEASE NOTES --functions fixed a bug in mod a test <!-- END RELEASE NOTES --