diff --git a/bin/coverage_doctest.py b/bin/coverage_doctest.py index 7c9b5d17c81..98284dd8a9b 100755 --- a/bin/coverage_doctest.py +++ b/bin/coverage_doctest.py @@ -265,7 +265,7 @@ def handle_starttag(self, tag, attr): self.is_imported.append(a['id']) def find_sphinx(name, mod_path, found={}): - if mod_path in found: # Cache results + if mod_path in found: # Cache results return name in found[mod_path] doc_path = mod_path.split('.') @@ -312,7 +312,7 @@ def process_function(name, c_name, b_obj, mod_path, f_sk, f_md, f_mdt, f_idt, else: if not obj.__doc__: add_md = True - elif not '>>>' in obj.__doc__: + elif '>>>' not in obj.__doc__: add_mdt = True elif _is_indirect(name, obj.__doc__): add_idt = True @@ -372,7 +372,7 @@ def process_class(c_name, obj, c_sk, c_md, c_mdt, c_idt, c_has_doctest, full_name = "LINE %d: %s" % (line_no, c_name) if not obj.__doc__: c_md.append(full_name) - elif not '>>>' in obj.__doc__: + elif '>>>' not in obj.__doc__: c_mdt.append(full_name) elif _is_indirect(c_name, obj.__doc__): c_idt.append(full_name) diff --git a/bin/mailmap_update.py b/bin/mailmap_update.py index 03a090f37d5..8be8b8bce8d 100755 --- a/bin/mailmap_update.py +++ b/bin/mailmap_update.py @@ -41,7 +41,7 @@ print(yellow("Please use a newer git version >= 1.8.4.2")) with open(os.path.realpath(os.path.join(__file__, os.path.pardir, - os.path.pardir, "doc/aboutus.rst"))) as fd: + os.path.pardir, "doc/aboutus.rst"))) as fd: AUTHORS = unicode(fd.read(), 'utf-8') authors = [] diff --git a/bin/strip_whitespace b/bin/strip_whitespace deleted file mode 100755 index 118add54cb5..00000000000 --- a/bin/strip_whitespace +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python - -from __future__ import print_function - -import os - - -def strip_file(filename, write, report): - # .readlines() retains \n chars, while .read().splitlines() does not. - # Assuming that whitespace errors will be few, we will thus only need - # to re-add \n to a few right-stripped lines. The hit flag will keep us - # from unecessarily re-writing files with no changes. - - # without "b" all lines appear as \n terminated - with open(filename, 'rb') as f: - lines = f.readlines() - hit = False - cr = False - extra = 0 - for index, line in enumerate(lines): - if line.endswith(" \n"): - if report: - print("%s, line %s" % (filename, index + 1)) - if write: - lines[index] = line.rstrip() + "\n" - hit = True - if line.endswith("\r\n"): - if report and not cr: - print("%s, line %s (crlf now silent)" % (filename, index + 1)) - cr = True - if write: - lines[index] = line.rstrip() + "\n" - hit = True - - # correct no newline at eof - if lines and not lines[-1].endswith("\n"): - lines[-1] += "\n" - if report: - print("%s, no newline at eof" % filename) - if write: - hit = True - - # correct multiple newlines at eof - while len(lines) > 1 and lines[-1] == "\n" and lines[-2].endswith("\n"): - if write: - hit = True - lines.pop() - extra += 1 - - if extra > 0 and report: - print("%s, %d extra newlines at eof" % (filename, extra)) - - if write and hit: - # without "b" the lines may be written in sys-dep format - with open(filename, "wb") as f: - f.writelines(lines) - - -def go(path, write, report): - allowed_ext = [ - ".cpp", - ".cc", - ".h", - ".py", - ".rst", - ] - for root, dirs, files in os.walk(path): - for b in [".git"]: - if b in dirs: - dirs.remove(b) - for file in files: - if os.path.splitext(file)[1] not in allowed_ext: - continue - filename = os.path.join(root, file) - strip_file(filename, write, report) - - -def main(): - from optparse import OptionParser - p = OptionParser("usage: %prog [options] filename") - p.add_option("-d", "--dry", action="store_true", dest="dry", - help="Do not modify files.") - p.add_option("-v", "--verbose", action="store_true", dest="verbose", - help="Report all changes.") - p.add_option("-r", "--recursive", action="store_true", dest="recursive", - help="Recursively correct all files in a directory.") - options, args = p.parse_args() - if options.dry: - options.verbose = True - if len(args) == 1: - if options.recursive: - go(args[0], not options.dry, options.verbose) - else: - strip_file(args[0], not options.dry, options.verbose) - else: - p.print_help() - -if __name__ == "__main__": - main() diff --git a/doc/pics/pngview1.png b/doc/pics/pngview1.png deleted file mode 100644 index fa151694bfa..00000000000 Binary files a/doc/pics/pngview1.png and /dev/null differ diff --git a/examples/intermediate/infinite_1d_box.py b/examples/intermediate/infinite_1d_box.py index d9ff5f21b9d..02331fc6b15 100755 --- a/examples/intermediate/infinite_1d_box.py +++ b/examples/intermediate/infinite_1d_box.py @@ -60,8 +60,9 @@ def energy_corrections(perturbation, n, a=10, mass=0.5): """ x, _a = var("x _a") - Vnm = lambda n, m, a: Integral(X_n(n, a, x) * X_n(m, a, x) - * perturbation.subs({_a: a}), (x, 0, a)).n() + def Vnm(n, m, a): + return Integral(X_n(n, a, x) * X_n(m, a, x) + * perturbation.subs({_a: a}), (x, 0, a)).n() # As we know from theory for V0*r/a we will just V(n, n-1) and V(n, n+1) # wouldn't equals zero diff --git a/setup.cfg b/setup.cfg index 6e528ffbebd..1f524546831 100644 --- a/setup.cfg +++ b/setup.cfg @@ -8,7 +8,22 @@ # E113 - unexpected indentation # W292 - no newline at end of file # W391 - blank line at end of file -select = E101,W191,W291,W293,E111,E112,E113,W292,W391 +# E211 - whitespace before ‘(‘ +# E272 - multiple spaces before keyword +# E701 - multiple statements on one line (colon) +# E262 - inline comment should start with ‘# ‘ +# E703 - statement ends with a semicolon +# E714 - test for object identity should be ‘is not’ +# E125 - continuation line with same indent as next logical line +# E271 - multiple spaces after keyword +# E713 - test for membership should be ‘not in’ +# E711 - comparison to None should be ‘if cond is None:’ +# E731 - do not assign a lambda expression, use a def +# E702 - multiple statements on one line (semicolon) +# E303 - too many blank lines (3) +# E261 - at least two spaces before inline comment +# E721 - do not compare types, use ‘isinstance()’ +select = E101,W191,W291,W293,E111,E112,E113,W292,W391,E211,E272,E701,E262,E703,E714,E125,E271,E713,E711,E731,E702,E303,E261,E721 [pytest] minversion = 2.7.0 doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL diff --git a/sympy/abc.py b/sympy/abc.py index fc7d995ec61..981cee61e24 100644 --- a/sympy/abc.py +++ b/sympy/abc.py @@ -60,7 +60,7 @@ _latin = list(string.ascii_letters) # OSINEQ should not be imported as they clash; gamma, pi and zeta clash, too -_greek = list(greeks) # make a copy, so we can mutate it +_greek = list(greeks) # make a copy, so we can mutate it # Note: We import lamda since lambda is a reserved keyword in Python _greek.remove("lambda") _greek.append("lamda") diff --git a/sympy/assumptions/ask.py b/sympy/assumptions/ask.py index a93adecff83..3a5edfd091b 100644 --- a/sympy/assumptions/ask.py +++ b/sympy/assumptions/ask.py @@ -81,7 +81,7 @@ def _extract_facts(expr, symbol): args = [x for x in args if x is not None] if args: return expr.func(*args) - if args and all(x != None for x in args): + if args and all(x is not None for x in args): return expr.func(*args) diff --git a/sympy/assumptions/handlers/sets.py b/sympy/assumptions/handlers/sets.py index 30e3168a443..64776fc74ea 100644 --- a/sympy/assumptions/handlers/sets.py +++ b/sympy/assumptions/handlers/sets.py @@ -128,7 +128,7 @@ def Pow(expr, assumptions): return False Rational, Float = \ - [staticmethod(CommonHandler.AlwaysTrue)]*2 # Float is finite-precision + [staticmethod(CommonHandler.AlwaysTrue)]*2 # Float is finite-precision ImaginaryUnit, Infinity, NegativeInfinity, Pi, Exp1, GoldenRatio = \ [staticmethod(CommonHandler.AlwaysFalse)]*6 @@ -386,7 +386,7 @@ def Add(expr, assumptions): Mul, Pow = [Add]*2 Number, sin, cos, log, exp, re, im, NumberSymbol, Abs, ImaginaryUnit = \ - [staticmethod(CommonHandler.AlwaysTrue)]*10 # they are all complex functions or expressions + [staticmethod(CommonHandler.AlwaysTrue)]*10 # they are all complex functions or expressions Infinity, NegativeInfinity = [staticmethod(CommonHandler.AlwaysFalse)]*2 @@ -507,7 +507,6 @@ def Pow(expr, assumptions): return ask(Q.negative(expr.base), assumptions) return half - @staticmethod def log(expr, assumptions): if ask(Q.extended_real(expr.args[0]), assumptions): diff --git a/sympy/assumptions/tests/test_context.py b/sympy/assumptions/tests/test_context.py index be162f1c694..5cef46ead20 100644 --- a/sympy/assumptions/tests/test_context.py +++ b/sympy/assumptions/tests/test_context.py @@ -36,4 +36,4 @@ def test_remove_safe(): global_assumptions.remove(Q.integer(x)) assert not ask(Q.integer(x)) assert ask(Q.integer(x)) - global_assumptions.clear() # for the benefit of other tests + global_assumptions.clear() # for the benefit of other tests diff --git a/sympy/combinatorics/perm_groups.py b/sympy/combinatorics/perm_groups.py index 94b9303196a..240ec6a1ecf 100644 --- a/sympy/combinatorics/perm_groups.py +++ b/sympy/combinatorics/perm_groups.py @@ -61,7 +61,7 @@ class PermutationGroup(Basic): >>> P = Polyhedron(list('ABC'), pgroup=G) >>> P.corners (A, B, C) - >>> P.rotate(0) # apply permutation 0 + >>> P.rotate(0) # apply permutation 0 >>> P.corners (A, C, B) >>> P.reset() @@ -517,7 +517,7 @@ def baseswap(self, base, strong_gens, pos, randomized=False, while len(_orbit(degree, T, base[pos])) != size: gamma = next(iter(Gamma)) x = transversals[pos][gamma] - temp = x._array_form.index(base[pos + 1]) # (~x)(base[pos + 1]) + temp = x._array_form.index(base[pos + 1]) # (~x)(base[pos + 1]) if temp not in basic_orbits[pos + 1]: Gamma = Gamma - _orbit(degree, T, gamma) else: @@ -765,7 +765,8 @@ def centralizer(self, other): rep = orbit_reps[j] transversals[j] = dict( other.orbit_transversal(rep, pairs=True)) - trivial_test = lambda x: True + def trivial_test(x): + return True tests = [None]*base_len for l in range(base_len): if base[l] in orbit_reps: @@ -1114,7 +1115,7 @@ def derived_subgroup(self): for k in rng: c[p2[p1[k]]] = p1[p2[k]] ct = tuple(c) - if not ct in set_commutators: + if ct not in set_commutators: set_commutators.add(ct) cms = [_af_new(p) for p in set_commutators] G2 = self.normal_closure(cms) @@ -1345,7 +1346,7 @@ def contains(self, g, strict=True): >>> a = Permutation(1, 2) >>> b = Permutation(2, 3, 1) >>> G = PermutationGroup(a, b, degree=5) - >>> G.contains(G[0]) # trivial check + >>> G.contains(G[0]) # trivial check True >>> elem = Permutation([[2, 3]], size=5) >>> G.contains(elem) @@ -2103,7 +2104,7 @@ def orbit_rep(self, alpha, beta, schreier_vector=None): a = [] while k != -1: a.append(gens[k]) - beta = gens[k].index(beta) # beta = (~gens[k])(beta) + beta = gens[k].index(beta) # beta = (~gens[k])(beta) k = schreier_vector[beta] if a: return _af_new(_af_rmuln(*a)) @@ -2197,7 +2198,7 @@ def order(self): degree """ - if self._order != None: + if self._order is not None: return self._order if self._is_sym: n = self._degree @@ -2614,7 +2615,7 @@ def schreier_sims_random(self, base=None, gens=None, consec_succ=10, >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(5) >>> base, strong_gens = S.schreier_sims_random(consec_succ=5) - >>> _verify_bsgs(S, base, strong_gens) #doctest: +SKIP + >>> _verify_bsgs(S, base, strong_gens) # doctest: +SKIP True Notes @@ -2923,7 +2924,8 @@ def update_nu(l): if init_subgroup is None: init_subgroup = PermutationGroup([identity]) if tests is None: - trivial_test = lambda x: True + def trivial_test(x): + return True tests = [] for i in range(base_len): tests.append(trivial_test) diff --git a/sympy/combinatorics/permutations.py b/sympy/combinatorics/permutations.py index 655d186467a..99dda738412 100644 --- a/sympy/combinatorics/permutations.py +++ b/sympy/combinatorics/permutations.py @@ -850,7 +850,6 @@ def __new__(cls, *args, **kwargs): raise ValueError("Permutation argument must be a list of ints, " "a list of lists, Permutation or Cycle.") - # safe to assume args are valid; this also makes a copy # of the args args = list(args[0]) @@ -1698,7 +1697,7 @@ def rank(self): next_lex, unrank_lex, cardinality, length, order, size """ - if not self._rank is None: + if self._rank is not None: return self._rank rank = 0 rho = self.array_form[:] diff --git a/sympy/combinatorics/subsets.py b/sympy/combinatorics/subsets.py index 1fb8fb6bd1c..0a5b3ee208f 100644 --- a/sympy/combinatorics/subsets.py +++ b/sympy/combinatorics/subsets.py @@ -158,7 +158,7 @@ def next_lexicographic(self): else: indices.remove(i) i = i - 1 - while not i in indices and i >= 0: + while i not in indices and i >= 0: i = i - 1 if i >= 0: indices.remove(i) diff --git a/sympy/combinatorics/tensor_can.py b/sympy/combinatorics/tensor_can.py index cea9f97ab63..72dd9060c96 100644 --- a/sympy/combinatorics/tensor_can.py +++ b/sympy/combinatorics/tensor_can.py @@ -755,7 +755,7 @@ def canonicalize(g, dummies, msym, *v): """ from sympy.combinatorics.testutil import canonicalize_naive if not isinstance(msym, list): - if not msym in [0, 1, None]: + if msym not in [0, 1, None]: raise ValueError('msym must be 0, 1 or None') num_types = 1 else: diff --git a/sympy/combinatorics/tests/test_perm_groups.py b/sympy/combinatorics/tests/test_perm_groups.py index 950a631a96b..3f4476be7d4 100644 --- a/sympy/combinatorics/tests/test_perm_groups.py +++ b/sympy/combinatorics/tests/test_perm_groups.py @@ -517,10 +517,14 @@ def test_schreier_sims_incremental(): def _subgroup_search(i, j, k): - prop_true = lambda x: True - prop_fix_points = lambda x: [x(point) for point in points] == points - prop_comm_g = lambda x: rmul(x, g) == rmul(g, x) - prop_even = lambda x: x.is_even + def prop_true(x): + return True + def prop_fix_points(x): + return [x(point) for point in points] == points + def prop_comm_g(x): + return rmul(x, g) == rmul(g, x) + def prop_even(x): + return x.is_even for i in range(i, j, k): S = SymmetricGroup(i) A = AlternatingGroup(i) diff --git a/sympy/combinatorics/tests/test_tensor_can.py b/sympy/combinatorics/tests/test_tensor_can.py index 293b141069f..d864f8bfd28 100644 --- a/sympy/combinatorics/tests/test_tensor_can.py +++ b/sympy/combinatorics/tests/test_tensor_can.py @@ -309,7 +309,6 @@ def test_canonicalize1(): can = canonicalize(g, list(range(2,6)), 0, (base3, gens3, 2, 0)) assert can == [0,2,4,1,3,5,6,7] - # A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0 # ord = [a0,a1,a2,a3,d0,-d0,d1,-d1,d2,-d2,d3,-d3] # 0 1 2 3 4 5 6 7 8 9 10 11 @@ -500,7 +499,6 @@ def test_riemann_products(): can = canonicalize(g, dummies, 0, (base, gens, 2, 0)) assert can == [0, 3, 4, 1, 2, 5, 7, 6] - # A^n_{i, j} symmetric in i,j # A^m0_a0^d2 * A^n0_d2^d1 * A^n1_d1^d0 * A_{m0 d0}^a1 # ordering: first the free indices; then first n, then d diff --git a/sympy/combinatorics/testutil.py b/sympy/combinatorics/testutil.py index 939830fe472..9f0659b3d70 100644 --- a/sympy/combinatorics/testutil.py +++ b/sympy/combinatorics/testutil.py @@ -61,7 +61,8 @@ def _naive_list_centralizer(self, other, af=False): if hasattr(other, 'generators'): elements = list(self.generate_dimino(af=True)) gens = [x._array_form for x in other.generators] - commutes_with_gens = lambda x: all(_af_commutes_with(x, gen) for gen in gens) + def commutes_with_gens(x): + return all(_af_commutes_with(x, gen) for gen in gens) centralizer_list = [] if not af: for element in elements: diff --git a/sympy/combinatorics/util.py b/sympy/combinatorics/util.py index 44c8f684b85..d514535969e 100644 --- a/sympy/combinatorics/util.py +++ b/sympy/combinatorics/util.py @@ -101,7 +101,7 @@ def _check_cycles_alt_sym(perm): total_len = 0 used = set() for i in range(n//2): - if not i in used and i < n//2 - total_len: + if i not in used and i < n//2 - total_len: current_len = 1 used.add(i) j = i diff --git a/sympy/concrete/expr_with_intlimits.py b/sympy/concrete/expr_with_intlimits.py index d4c77ba9f26..3a5750432ca 100644 --- a/sympy/concrete/expr_with_intlimits.py +++ b/sympy/concrete/expr_with_intlimits.py @@ -130,7 +130,6 @@ def change_index(self, var, trafo, newvar=None): return self.func(function, *limits) - def index(expr, x): """ Return the index of a dummy variable in the list of limits. @@ -237,7 +236,6 @@ def reorder(expr, *arg): return new_expr - def reorder_limit(expr, x, y): """ Interchange two limit tuples of a Sum or Product expression. diff --git a/sympy/concrete/summations.py b/sympy/concrete/summations.py index 33d97436b81..ee774ce4925 100644 --- a/sympy/concrete/summations.py +++ b/sympy/concrete/summations.py @@ -340,7 +340,6 @@ def fpoint(expr): g = g.diff(i, 2, simplify=False) return s + iterm, abs(term) - def reverse_order(self, *indices): """ Reverse the order of a limit in a Sum. @@ -710,7 +709,7 @@ def eval_sum_symbolic(f, limits): if None not in (lsum, rsum): r = lsum + rsum - if not r is S.NaN: + if r is not S.NaN: return r # Polynomial terms with Faulhaber's formula @@ -722,8 +721,8 @@ def eval_sum_symbolic(f, limits): if n.is_Integer: if n >= 0: - if (b is S.Infinity and not a is S.NegativeInfinity) or \ - (a is S.NegativeInfinity and not b is S.Infinity): + if (b is S.Infinity and a is not S.NegativeInfinity) or \ + (a is S.NegativeInfinity and b is not S.Infinity): return S.Infinity return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand() elif a.is_Integer and a >= 1: @@ -752,7 +751,7 @@ def eval_sum_symbolic(f, limits): r = gosper_sum(f, (i, a, b)) - if not r in (None, S.NaN): + if r not in (None, S.NaN): return r return eval_sum_hyper(f_orig, (i, a, b)) diff --git a/sympy/core/add.py b/sympy/core/add.py index 8c947a033ff..4a539640d32 100644 --- a/sympy/core/add.py +++ b/sympy/core/add.py @@ -445,24 +445,32 @@ def _eval_is_algebraic_expr(self, syms): return all(term._eval_is_algebraic_expr(syms) for term in self.args) # assumption methods - _eval_is_extended_real = lambda self: _fuzzy_group( - (a.is_extended_real for a in self.args), quick_exit=True) - _eval_is_complex = lambda self: _fuzzy_group( - (a.is_complex for a in self.args), quick_exit=True) - _eval_is_antihermitian = lambda self: _fuzzy_group( - (a.is_antihermitian for a in self.args), quick_exit=True) - _eval_is_finite = lambda self: _fuzzy_group( - (a.is_finite for a in self.args), quick_exit=True) - _eval_is_hermitian = lambda self: _fuzzy_group( - (a.is_hermitian for a in self.args), quick_exit=True) - _eval_is_integer = lambda self: _fuzzy_group( - (a.is_integer for a in self.args), quick_exit=True) - _eval_is_rational = lambda self: _fuzzy_group( - (a.is_rational for a in self.args), quick_exit=True) - _eval_is_algebraic = lambda self: _fuzzy_group( - (a.is_algebraic for a in self.args), quick_exit=True) - _eval_is_commutative = lambda self: _fuzzy_group( - a.is_commutative for a in self.args) + def _eval_is_extended_real(self): + return _fuzzy_group((a.is_extended_real for a in self.args), quick_exit=True) + + def _eval_is_complex(self): + return _fuzzy_group((a.is_complex for a in self.args), quick_exit=True) + + def _eval_is_antihermitian(self): + return _fuzzy_group((a.is_antihermitian for a in self.args), quick_exit=True) + + def _eval_is_finite(self): + return _fuzzy_group((a.is_finite for a in self.args), quick_exit=True) + + def _eval_is_hermitian(self): + return _fuzzy_group((a.is_hermitian for a in self.args), quick_exit=True) + + def _eval_is_integer(self): + return _fuzzy_group((a.is_integer for a in self.args), quick_exit=True) + + def _eval_is_rational(self): + return _fuzzy_group((a.is_rational for a in self.args), quick_exit=True) + + def _eval_is_algebraic(self): + return _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True) + + def _eval_is_commutative(self): + return _fuzzy_group(a.is_commutative for a in self.args) def _eval_is_imaginary(self): rv = _fuzzy_group(a.is_imaginary for a in self.args) diff --git a/sympy/core/assumptions.py b/sympy/core/assumptions.py index dea69273299..ed0afbfed4c 100644 --- a/sympy/core/assumptions.py +++ b/sympy/core/assumptions.py @@ -212,7 +212,7 @@ class StdFactKB(FactKB): def __init__(self, facts=None): # save a copy of the facts dict if not facts: - self._generator = {}; + self._generator = {} elif not isinstance(facts, FactKB): self._generator = facts.copy() else: diff --git a/sympy/core/basic.py b/sympy/core/basic.py index 7c01fa32dbe..2cc1abfe575 100644 --- a/sympy/core/basic.py +++ b/sympy/core/basic.py @@ -500,7 +500,6 @@ def canonical_variables(self): return dict(list(zip(V, [Symbol(name % i, **v.assumptions0) for i, v in enumerate(V)]))) - def rcall(self, *args): """Apply on the argument recursively through the expression tree. @@ -1254,18 +1253,19 @@ def replace(self, query, value, map=False, simultaneous=True, exact=False): except SympifyError: pass if isinstance(query, type): - _query = lambda expr: isinstance(expr, query) + def _query(expr): + return isinstance(expr, query) - if isinstance(value, type): - _value = lambda expr, result: value(*expr.args) - elif callable(value): - _value = lambda expr, result: value(*expr.args) + if isinstance(value, type) or callable(value): + def _value(expr, result): + return value(*expr.args) else: raise TypeError( "given a type, replace() expects another " "type or a callable") elif isinstance(query, Basic): - _query = lambda expr: expr.match(query) + def _query(expr): + return expr.match(query) # XXX remove the exact flag and make multi-symbol # patterns use exact=True semantics; to do this the query must @@ -1276,22 +1276,24 @@ def replace(self, query, value, map=False, simultaneous=True, exact=False): # parameters it has. if isinstance(value, Basic): if exact: - _value = lambda expr, result: (value.subs(result) - if all(val for val in result.values()) else expr) + def _value(expr, result): + return (value.subs(result) \ + if all(val for val in result.values()) else expr) else: - _value = lambda expr, result: value.subs(result) + def _value(expr, result): + return value.subs(result) elif callable(value): # match dictionary keys get the trailing underscore stripped # from them and are then passed as keywords to the callable; # if ``exact`` is True, only accept match if there are no null # values amongst those matched. if exact: - _value = lambda expr, result: (value(**{ - str(key)[:-1]: val for key, val in result.items()}) - if all(val for val in result.values()) else expr) + def _value(expr, result): + return (value(**{str(key)[:-1]: val for key, val in result.items()}) + if all(val for val in result.values()) else expr) else: - _value = lambda expr, result: value(**{ - str(key)[:-1]: val for key, val in result.items()}) + def _value(expr, result): + return value(**{str(key)[:-1]: val for key, val in result.items()}) else: raise TypeError( "given an expression, replace() expects " @@ -1300,7 +1302,8 @@ def replace(self, query, value, map=False, simultaneous=True, exact=False): _query = query if callable(value): - _value = lambda expr, result: value(expr) + def _value(expr, result): + return value(expr) else: raise TypeError( "given a callable, replace() expects " diff --git a/sympy/core/compatibility.py b/sympy/core/compatibility.py index b05ee1ac091..ab19cc9a35a 100644 --- a/sympy/core/compatibility.py +++ b/sympy/core/compatibility.py @@ -289,7 +289,7 @@ def is_sequence(i, include=None): try: from itertools import zip_longest -except ImportError: # <= Python 2.7 +except ImportError: # <= Python 2.7 from itertools import izip_longest as zip_longest @@ -307,7 +307,7 @@ def as_int(n): >>> from sympy import sqrt >>> 3.0 3.0 - >>> as_int(3.0) # convert to int and test for equality + >>> as_int(3.0) # convert to int and test for equality 3 >>> int(sqrt(10)) 3 diff --git a/sympy/core/evalf.py b/sympy/core/evalf.py index a0139768746..7931739c8b2 100644 --- a/sympy/core/evalf.py +++ b/sympy/core/evalf.py @@ -1166,7 +1166,7 @@ def evalf_symbol(x, prec, options): return None, None, None, None return val._mpf_, None, prec, None else: - if not '_cache' in options: + if '_cache' not in options: options['_cache'] = {} cache = options['_cache'] cached, cached_prec = cache.get(x.name, (None, MINUS_INF)) @@ -1269,7 +1269,7 @@ def evalf(x, prec, options): if options.get("verbose"): print("### input", x) print("### output", to_str(r[0] or fzero, 50)) - print("### raw", r ) # r[0], r[2] + print("### raw", r ) # r[0], r[2] print() chop = options.get('chop', False) if chop: diff --git a/sympy/core/expr.py b/sympy/core/expr.py index 068b90a4985..164140520b3 100644 --- a/sympy/core/expr.py +++ b/sympy/core/expr.py @@ -2675,7 +2675,7 @@ def nseries(self, x=None, x0=0, n=6, dir='+', logx=None): >>> e.nseries(x, 0, 2, logx=logx) exp(logx*y) """ - if x and not x in self.free_symbols: + if x and x not in self.free_symbols: return self if x is None or x0 or dir != '+': # {see XPOS above} or (x.is_positive == x.is_negative == None): return self.series(x, x0, n, dir) diff --git a/sympy/core/mul.py b/sympy/core/mul.py index 69b34fca345..f432d4125e8 100644 --- a/sympy/core/mul.py +++ b/sympy/core/mul.py @@ -174,7 +174,7 @@ def flatten(cls, seq): a, b = seq if b.is_Rational: a, b = b, a - assert not a is S.One + assert a is not S.One if not a.is_zero and a.is_Rational: r, b = b.as_coeff_Mul() if b.is_Add: @@ -962,12 +962,14 @@ def _eval_is_rational_function(self, syms): def _eval_is_algebraic_expr(self, syms): return all(term._eval_is_algebraic_expr(syms) for term in self.args) - _eval_is_finite = lambda self: _fuzzy_group( - a.is_finite for a in self.args) - _eval_is_commutative = lambda self: _fuzzy_group( - a.is_commutative for a in self.args) - _eval_is_complex = lambda self: _fuzzy_group( - (a.is_complex for a in self.args), quick_exit=True) + def _eval_is_finite(self): + return _fuzzy_group(a.is_finite for a in self.args) + + def _eval_is_commutative(self): + return _fuzzy_group(a.is_commutative for a in self.args) + + def _eval_is_complex(self): + return _fuzzy_group((a.is_complex for a in self.args), quick_exit=True) def _eval_is_infinite(self): if any(a.is_infinite for a in self.args): diff --git a/sympy/core/power.py b/sympy/core/power.py index 7ee2d2b96f6..4573e741f6d 100644 --- a/sympy/core/power.py +++ b/sympy/core/power.py @@ -1313,7 +1313,7 @@ def _eval_as_leading_term(self, x): return exp(self.exp * log(self.base)).as_leading_term(x) @cacheit - def _taylor_term(self, n, x, *previous_terms): # of (1+x)**e + def _taylor_term(self, n, x, *previous_terms): # of (1+x)**e from sympy import binomial return binomial(self.exp, n) * self.func(x, n) diff --git a/sympy/core/symbol.py b/sympy/core/symbol.py index 16d9a11f2a2..6cb7512254f 100644 --- a/sympy/core/symbol.py +++ b/sympy/core/symbol.py @@ -151,7 +151,7 @@ def as_real_imag(self, deep=True, **hints): def is_constant(self, *wrt, **flags): if not wrt: return False - return not self in wrt + return self not in wrt @property def free_symbols(self): diff --git a/sympy/core/sympify.py b/sympy/core/sympify.py index 5cc43aa8e13..626cf55c6c9 100644 --- a/sympy/core/sympify.py +++ b/sympy/core/sympify.py @@ -245,7 +245,7 @@ def sympify(a, locals=None, convert_xor=True, strict=False, rational=False, cls = type(a) if cls in sympy_classes: return a - if cls is type(None): + if isinstance(cls, type(None)): if strict: raise SympifyError(a) else: diff --git a/sympy/core/tests/test_arit.py b/sympy/core/tests/test_arit.py index 3869d8f6ec7..23aa6be7b67 100644 --- a/sympy/core/tests/test_arit.py +++ b/sympy/core/tests/test_arit.py @@ -1828,7 +1828,6 @@ def test(z, b, e): else: assert e.is_zero is False - for iz, ib in cartes(*[[True, False, None]]*2): z = Dummy('z', nonzero=iz) b = Dummy('f', finite=ib) diff --git a/sympy/core/tests/test_compatibility.py b/sympy/core/tests/test_compatibility.py index fb46dcb4251..4ca7f082ed5 100644 --- a/sympy/core/tests/test_compatibility.py +++ b/sympy/core/tests/test_compatibility.py @@ -6,7 +6,8 @@ def test_default_sort_key(): - func = lambda x: x + def func(x): + return x assert sorted([func, x, func], key=default_sort_key) == [func, func, x] diff --git a/sympy/core/tests/test_containers.py b/sympy/core/tests/test_containers.py index 7e344aef135..d8cda36ebc0 100644 --- a/sympy/core/tests/test_containers.py +++ b/sympy/core/tests/test_containers.py @@ -128,7 +128,7 @@ def test_Dict(): assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S(1), S(2), S(3)} assert d.get(5, 'default') == 'default' - assert x in d and z in d and not 5 in d + assert x in d and z in d and 5 not in d assert d.has(x) and d.has(1) # SymPy Basic .has method # Test input types diff --git a/sympy/core/tests/test_evalf.py b/sympy/core/tests/test_evalf.py index ef121ba2103..55df02f3c49 100644 --- a/sympy/core/tests/test_evalf.py +++ b/sympy/core/tests/test_evalf.py @@ -148,7 +148,8 @@ def test_evalf_trig(): def test_evalf_near_integers(): # Binet's formula - f = lambda n: ((1 + sqrt(5))**n)/(2**n * sqrt(5)) + def f(n): + return ((1 + sqrt(5))**n)/(2**n * sqrt(5)) assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046' # Some near-integer identities from # http://mathworld.wolfram.com/AlmostInteger.html diff --git a/sympy/core/tests/test_evaluate.py b/sympy/core/tests/test_evaluate.py index 51d726c1f6c..f4e94bafcb9 100644 --- a/sympy/core/tests/test_evaluate.py +++ b/sympy/core/tests/test_evaluate.py @@ -16,7 +16,6 @@ def test_add(): assert isinstance(x + x, Mul) - def test_nested(): with evaluate(False): expr = (x + x) + (y + y) diff --git a/sympy/core/tests/test_facts.py b/sympy/core/tests/test_facts.py index 608ac554368..2b9ae1c95df 100644 --- a/sympy/core/tests/test_facts.py +++ b/sympy/core/tests/test_facts.py @@ -47,7 +47,6 @@ def D(i): 'c'}, Not('c'): {Not('a'), 'b'},} assert P == {'a': {'b', 'c'}, 'b': {'a', 'c'}, 'c': {'a', 'b'}} - # Long deductions I, P = D([('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]) assert I == {'a': {'b', 'c', 'd', 'e'}, 'b': {'c', 'd', 'e'}, diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py index 15bc6987ed8..1773b61f91f 100644 --- a/sympy/core/tests/test_numbers.py +++ b/sympy/core/tests/test_numbers.py @@ -777,7 +777,7 @@ def test_NaN(): assert nan + S.One == nan assert nan/S.One == nan assert nan**0 == 1 # as per IEEE 754 - assert 1**nan == nan # IEEE 754 is not the best choice for symbolic work + assert 1**nan == nan # IEEE 754 is not the best choice for symbolic work # test Pow._eval_power's handling of NaN assert Pow(nan, 0, evaluate=False)**2 == 1 diff --git a/sympy/core/tests/test_symbol.py b/sympy/core/tests/test_symbol.py index 8d96ae7ba01..013ca018237 100644 --- a/sympy/core/tests/test_symbol.py +++ b/sympy/core/tests/test_symbol.py @@ -168,10 +168,14 @@ def test_Wild_properties(): given_patterns = [ x, y, p, k, -k, n, -n, sympify(-3), sympify(3), pi, Rational(3, 2), I ] - integerp = lambda k: k.is_integer - positivep = lambda k: k.is_positive - symbolp = lambda k: k.is_Symbol - realp = lambda k: k.is_extended_real + def integerp(k): + return k.is_integer + def positivep(k): + return k.is_positive + def symbolp(k): + return k.is_Symbol + def realp(k): + return k.is_extended_real S = Wild("S", properties=[symbolp]) R = Wild("R", properties=[realp]) @@ -289,7 +293,6 @@ def test_symbols(): assert symbols('aa:d,x:z') == (aa, ab, ac, ad, x, y, z) assert symbols(('aa:d','x:z')) == ((aa, ab, ac, ad), (x, y, z)) - # issue 6675 def sym(s): return str(symbols(s)) diff --git a/sympy/core/tests/test_sympify.py b/sympy/core/tests/test_sympify.py index dab39103c49..2267f3eaf66 100644 --- a/sympy/core/tests/test_sympify.py +++ b/sympy/core/tests/test_sympify.py @@ -17,7 +17,7 @@ def test_issue_3538(): v = sympify("exp(x)") assert v == exp(x) - assert type(v) == type(exp(x)) + assert isinstance(v, exp) assert str(type(v)) == str(type(exp(x))) @@ -226,8 +226,8 @@ def test_lambda(): def test_lambda_raises(): - raises(SympifyError, lambda: sympify("lambda *args: args")) # args argument error - raises(SympifyError, lambda: sympify("lambda **kwargs: kwargs[0]")) # kwargs argument error + raises(SympifyError, lambda: sympify("lambda *args: args")) # args argument error + raises(SympifyError, lambda: sympify("lambda **kwargs: kwargs[0]")) # kwargs argument error raises(SympifyError, lambda: sympify("lambda x = 1: x")) # Keyword argument error with raises(SympifyError): _sympify('lambda: 1') diff --git a/sympy/functions/combinatorial/factorials.py b/sympy/functions/combinatorial/factorials.py index 07ccd16c7e9..3828dc2802c 100644 --- a/sympy/functions/combinatorial/factorials.py +++ b/sympy/functions/combinatorial/factorials.py @@ -739,4 +739,5 @@ def _eval_rewrite_as_gamma(self, n, k): return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1)) def _eval_is_integer(self): - return self.args[0].is_integer and self.args[1].is_integer + if self.args[0].is_integer and self.args[1].is_integer: + return True diff --git a/sympy/functions/combinatorial/numbers.py b/sympy/functions/combinatorial/numbers.py index 8a7f58ee372..661863179ab 100644 --- a/sympy/functions/combinatorial/numbers.py +++ b/sympy/functions/combinatorial/numbers.py @@ -625,7 +625,7 @@ def eval(cls, n, m=None): if n.is_Integer and n.is_nonnegative and m.is_Integer: if n == 0: return S.Zero - if not m in cls._functions: + if m not in cls._functions: @recurrence_memo([0]) def f(n, prev): return prev[-1] + S.One / n**m @@ -1029,7 +1029,6 @@ def _eval_is_prime(self): return (n - 8).is_zero - ####################################################################### ### ### Functions for enumerating partitions, permutations and combinations diff --git a/sympy/functions/combinatorial/tests/test_comb_factorials.py b/sympy/functions/combinatorial/tests/test_comb_factorials.py index 35d595d3fde..f03e69c1213 100644 --- a/sympy/functions/combinatorial/tests/test_comb_factorials.py +++ b/sympy/functions/combinatorial/tests/test_comb_factorials.py @@ -232,7 +232,6 @@ def test_factorial2(): assert factorial2(tfo).is_odd is None - def test_binomial(): n = Symbol('n', integer=True) nz = Symbol('nz', integer=True, nonzero=True) diff --git a/sympy/functions/combinatorial/tests/test_comb_numbers.py b/sympy/functions/combinatorial/tests/test_comb_numbers.py index 29e3086e506..af2851d2ba0 100644 --- a/sympy/functions/combinatorial/tests/test_comb_numbers.py +++ b/sympy/functions/combinatorial/tests/test_comb_numbers.py @@ -431,7 +431,7 @@ def test_nC_nP_nT(): 1, -5040, 13068, -13132, 6769, -1960, 322, -28, 1, 40320, -109584, 118124, -67284, 22449, -4536, 546, -36, 1] # http://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind - assert [stirling(n, k, kind=1) + assert [stirling(n, k, kind=1) for n in range(10) for k in range(n+1)] == [ 1, 0, 1, diff --git a/sympy/functions/elementary/exponential.py b/sympy/functions/elementary/exponential.py index 2e0274db9b6..9d4aa3e4c33 100644 --- a/sympy/functions/elementary/exponential.py +++ b/sympy/functions/elementary/exponential.py @@ -343,8 +343,9 @@ def _eval_subs(self, old, new): elif old is S.Exp1 and new.is_Function: old = exp if old.func is exp or old is S.Exp1: - f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if ( - a.is_Pow or a.func is exp) else a + def f(a): + return Pow(*a.as_base_exp(), evaluate=False) \ + if (a.is_Pow or a.func is exp) else a return Pow._eval_subs(f(self), f(old), new) if old is exp and not new.is_Function: diff --git a/sympy/functions/elementary/hyperbolic.py b/sympy/functions/elementary/hyperbolic.py index 6eb03560e34..6fd24040bfd 100644 --- a/sympy/functions/elementary/hyperbolic.py +++ b/sympy/functions/elementary/hyperbolic.py @@ -156,7 +156,7 @@ def _eval_expand_trig(self, deep=True, **hints): else: arg = self.args[0] x = None - if arg.is_Add: # TODO, implement more if deep stuff here + if arg.is_Add: # TODO, implement more if deep stuff here x, y = arg.as_two_terms() else: coeff, terms = arg.as_coeff_Mul(rational=True) @@ -305,7 +305,7 @@ def _eval_expand_trig(self, deep=True, **hints): else: arg = self.args[0] x = None - if arg.is_Add: # TODO, implement more if deep stuff here + if arg.is_Add: # TODO, implement more if deep stuff here x, y = arg.as_two_terms() else: coeff, terms = arg.as_coeff_Mul(rational=True) @@ -633,7 +633,7 @@ def eval(cls, arg): t = cls._reciprocal_of.eval(arg) if hasattr(arg, 'inverse') and arg.inverse() == cls: return arg.args[0] - return 1/t if t != None else t + return 1/t if t is not None else t def _call_reciprocal(self, method_name, *args, **kwargs): # Calls method_name on _reciprocal_of @@ -644,13 +644,13 @@ def _calculate_reciprocal(self, method_name, *args, **kwargs): # If calling method_name on _reciprocal_of returns a value != None # then return the reciprocal of that value t = self._call_reciprocal(method_name, *args, **kwargs) - return 1/t if t != None else t + return 1/t if t is not None else t def _rewrite_reciprocal(self, method_name, arg): # Special handling for rewrite functions. If reciprocal rewrite returns # unmodified expression, then return None t = self._call_reciprocal(method_name, arg) - if t != None and t != self._reciprocal_of(arg): + if t is not None and t != self._reciprocal_of(arg): return 1/t def _eval_rewrite_as_exp(self, arg): diff --git a/sympy/functions/elementary/miscellaneous.py b/sympy/functions/elementary/miscellaneous.py index cb91b8ceac7..4ee7eb1e53f 100644 --- a/sympy/functions/elementary/miscellaneous.py +++ b/sympy/functions/elementary/miscellaneous.py @@ -461,7 +461,6 @@ def is_extended_real(self): return fuzzy_and(arg.is_extended_real for arg in self.args) - class Max(MinMaxBase, Application): """Return, if possible, the maximum value of the list. diff --git a/sympy/functions/elementary/piecewise.py b/sympy/functions/elementary/piecewise.py index 2571ec5ea36..074d11efaa9 100644 --- a/sympy/functions/elementary/piecewise.py +++ b/sympy/functions/elementary/piecewise.py @@ -474,28 +474,50 @@ def _eval_template_is_attr(self, is_attr, when_multiple=None): return when_multiple return b - _eval_is_finite = lambda self: self._eval_template_is_attr( - 'is_finite', when_multiple=False) - _eval_is_complex = lambda self: self._eval_template_is_attr('is_complex') - _eval_is_even = lambda self: self._eval_template_is_attr('is_even') - _eval_is_imaginary = lambda self: self._eval_template_is_attr( - 'is_imaginary') - _eval_is_integer = lambda self: self._eval_template_is_attr('is_integer') - _eval_is_irrational = lambda self: self._eval_template_is_attr( - 'is_irrational') - _eval_is_negative = lambda self: self._eval_template_is_attr('is_negative') - _eval_is_nonnegative = lambda self: self._eval_template_is_attr( - 'is_nonnegative') - _eval_is_nonpositive = lambda self: self._eval_template_is_attr( - 'is_nonpositive') - _eval_is_nonzero = lambda self: self._eval_template_is_attr( - 'is_nonzero', when_multiple=True) - _eval_is_odd = lambda self: self._eval_template_is_attr('is_odd') - _eval_is_polar = lambda self: self._eval_template_is_attr('is_polar') - _eval_is_positive = lambda self: self._eval_template_is_attr('is_positive') - _eval_is_extended_real = lambda self: self._eval_template_is_attr('is_extended_real') - _eval_is_zero = lambda self: self._eval_template_is_attr( - 'is_zero', when_multiple=False) + def _eval_is_finite(self): + return self._eval_template_is_attr('is_finite', when_multiple=False) + + def _eval_is_complex(self): + return self._eval_template_is_attr('is_complex') + + def _eval_is_even(self): + return self._eval_template_is_attr('is_even') + + def _eval_is_imaginary(self): + return self._eval_template_is_attr('is_imaginary') + + def _eval_is_integer(self): + return self._eval_template_is_attr('is_integer') + + def _eval_is_irrational(self): + return self._eval_template_is_attr('is_irrational') + + def _eval_is_negative(self): + return self._eval_template_is_attr('is_negative') + + def _eval_is_nonnegative(self): + return self._eval_template_is_attr('is_nonnegative') + + def _eval_is_nonpositive(self): + return self._eval_template_is_attr('is_nonpositive') + + def _eval_is_nonzero(self): + return self._eval_template_is_attr('is_nonzero', when_multiple=True) + + def _eval_is_odd(self): + return self._eval_template_is_attr('is_odd') + + def _eval_is_polar(self): + return self._eval_template_is_attr('is_polar') + + def _eval_is_positive(self): + return self._eval_template_is_attr('is_positive') + + def _eval_is_extended_real(self): + return self._eval_template_is_attr('is_extended_real') + + def _eval_is_zero(self): + return self._eval_template_is_attr('is_zero', when_multiple=False) @classmethod def __eval_cond(cls, cond): diff --git a/sympy/functions/elementary/tests/test_exponential.py b/sympy/functions/elementary/tests/test_exponential.py index 1188401f412..276c557fd59 100644 --- a/sympy/functions/elementary/tests/test_exponential.py +++ b/sympy/functions/elementary/tests/test_exponential.py @@ -277,7 +277,7 @@ def test_log_hashing(): e = log(log(x)) assert e.func is log - assert not x.func is log + assert x.func is not log assert hash(log(log(x))) != hash(x) assert e != x diff --git a/sympy/functions/elementary/tests/test_miscellaneous.py b/sympy/functions/elementary/tests/test_miscellaneous.py index aa897d38f3d..bab3c82438b 100644 --- a/sympy/functions/elementary/tests/test_miscellaneous.py +++ b/sympy/functions/elementary/tests/test_miscellaneous.py @@ -242,7 +242,6 @@ def test_rewrite_MaxMin_as_Heaviside(): 2*x*Heaviside(2*x)*Heaviside(x - 2) + \ (x + 2)*Heaviside(-x + 2)*Heaviside(x + 2) - assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x) assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \ 3*Heaviside(x - 3) diff --git a/sympy/functions/elementary/tests/test_piecewise.py b/sympy/functions/elementary/tests/test_piecewise.py index 16540f87915..611b6b11099 100644 --- a/sympy/functions/elementary/tests/test_piecewise.py +++ b/sympy/functions/elementary/tests/test_piecewise.py @@ -48,7 +48,6 @@ def test_piecewise(): assert p3.subs(x, 0.0) == 1 assert p4.subs(x, 0.0) == 1 - f, g, h = symbols('f,g,h', cls=Function) pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1)) pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1)) diff --git a/sympy/functions/elementary/tests/test_trigonometric.py b/sympy/functions/elementary/tests/test_trigonometric.py index bd6be49c015..c4590e964ce 100644 --- a/sympy/functions/elementary/tests/test_trigonometric.py +++ b/sympy/functions/elementary/tests/test_trigonometric.py @@ -1080,7 +1080,6 @@ def test_inverses(): assert acot(x).inverse() == cot - def test_real_imag(): a, b = symbols('a b', extended_real=True) z = a + b*I @@ -1134,11 +1133,11 @@ def test_tancot_rewrite_sqrt(): for i in range(1, (n + 1)//2 + 1): if 1 == gcd(i, n): x = i*pi/n - if 2*i != n and 3*i != 2*n: + if 2*i != n and 3*i != 2*n: t1 = tan(x).rewrite(sqrt) assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n) - if i != 0 and i != n: + if i != 0 and i != n: c1 = cot(x).rewrite(sqrt) assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n) @@ -1184,7 +1183,7 @@ def test_sec(): assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1) assert sec(x).is_extended_real == True - assert sec(z).is_extended_real == None + assert sec(z).is_extended_real is None assert sec(a).is_algebraic is None assert sec(na).is_algebraic is False @@ -1192,7 +1191,7 @@ def test_sec(): assert sec(x).as_leading_term() == sec(x) assert sec(0).is_finite == True - assert sec(x).is_finite == None + assert sec(x).is_finite is None assert sec(pi/2).is_finite == False assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6) @@ -1259,7 +1258,7 @@ def test_csc(): assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x)) assert csc(x).is_extended_real == True - assert csc(z).is_extended_real == None + assert csc(z).is_extended_real is None assert csc(a).is_algebraic is None assert csc(na).is_algebraic is False @@ -1267,7 +1266,7 @@ def test_csc(): assert csc(x).as_leading_term() == csc(x) assert csc(0).is_finite == False - assert csc(x).is_finite == None + assert csc(x).is_finite is None assert csc(pi/2).is_finite == True assert series(csc(x), x, x0=pi/2, n=6) == \ diff --git a/sympy/functions/elementary/trigonometric.py b/sympy/functions/elementary/trigonometric.py index d456aa3b77e..6fc561e0ab6 100644 --- a/sympy/functions/elementary/trigonometric.py +++ b/sympy/functions/elementary/trigonometric.py @@ -546,7 +546,7 @@ def eval(cls, arg): if q in table2: a, b = p*S.Pi/table2[q][0], p*S.Pi/table2[q][1] nvala, nvalb = cls(a), cls(b) - if None == nvala or None == nvalb: + if None is nvala or None is nvalb: return None return nvala*nvalb + cls(S.Pi/2 - a)*cls(S.Pi/2 - b) @@ -560,7 +560,7 @@ def eval(cls, arg): if 0 == q % 2: narg = (pi_coeff*2)*S.Pi nval = cls(narg) - if None == nval: + if None is nval: return None x = (2*pi_coeff + 1)/2 sign_cos = (-1)**((-1 if x < 0 else 1)*int(abs(x))) @@ -662,7 +662,7 @@ def ipartfrac(r, factors=None): if 2 > r.q*r.q: return r.q - if None == factors: + if None is factors: a = [n//x**y for x, y in factorint(r.q).items()] else: a = [n//x for x in factors] @@ -716,7 +716,7 @@ def fermatCoords(n): if 0 == pi_coeff.q % 2: # recursively remove powers of 2 narg = (pi_coeff*2)*S.Pi nval = cos(narg) - if None == nval: + if None is nval: return None nval = nval.rewrite(sqrt) x = (2*pi_coeff + 1)/2 @@ -894,7 +894,7 @@ def eval(cls, arg): p = pi_coeff.p % q if q in table2: nvala, nvalb = cls(p*S.Pi/table2[q][0]), cls(p*S.Pi/table2[q][1]) - if None == nvala or None == nvalb: + if None is nvala or None is nvalb: return None return (nvala - nvalb)/(1 + nvala*nvalb) narg = ((pi_coeff + S.Half) % 1 - S.Half)*S.Pi @@ -1162,7 +1162,7 @@ def eval(cls, arg): p = pi_coeff.p % q if q in table2: nvala, nvalb = cls(p*S.Pi/table2[q][0]), cls(p*S.Pi/table2[q][1]) - if None == nvala or None == nvalb: + if None is nvala or None is nvalb: return None return (1 + nvala*nvalb)/(nvalb - nvala) narg = (((pi_coeff + S.Half) % 1) - S.Half)*S.Pi @@ -1372,7 +1372,7 @@ def eval(cls, arg): t = cls._reciprocal_of.eval(arg) if hasattr(arg, 'inverse') and arg.inverse() == cls: return arg.args[0] - return 1/t if t != None else t + return 1/t if t is not None else t def _call_reciprocal(self, method_name, *args, **kwargs): # Calls method_name on _reciprocal_of @@ -1383,13 +1383,13 @@ def _calculate_reciprocal(self, method_name, *args, **kwargs): # If calling method_name on _reciprocal_of returns a value != None # then return the reciprocal of that value t = self._call_reciprocal(method_name, *args, **kwargs) - return 1/t if t != None else t + return 1/t if t is not None else t def _rewrite_reciprocal(self, method_name, arg): # Special handling for rewrite functions. If reciprocal rewrite returns # unmodified expression, then return None t = self._call_reciprocal(method_name, arg) - if t != None and t != self._reciprocal_of(arg): + if t is not None and t != self._reciprocal_of(arg): return 1/t def fdiff(self, argindex=1): diff --git a/sympy/functions/special/bessel.py b/sympy/functions/special/bessel.py index 541b716e360..d7c92039172 100644 --- a/sympy/functions/special/bessel.py +++ b/sympy/functions/special/bessel.py @@ -722,7 +722,8 @@ def jn_zeros(n, k, method="sympy", dps=15): elif method == "scipy": from scipy.special import sph_jn from scipy.optimize import newton - f = lambda x: sph_jn(n, x)[0][-1] + def f(x): + return sph_jn(n, x)[0][-1] else: raise NotImplementedError("Unknown method.") diff --git a/sympy/functions/special/error_functions.py b/sympy/functions/special/error_functions.py index 79da8524510..03fa849c646 100644 --- a/sympy/functions/special/error_functions.py +++ b/sympy/functions/special/error_functions.py @@ -102,7 +102,6 @@ def fdiff(self, argindex=1): else: raise ArgumentIndexError(self, argindex) - def inverse(self, argindex=1): """ Returns the inverse of this function. @@ -636,7 +635,6 @@ class erf2(Function): .. [1] http://functions.wolfram.com/GammaBetaErf/Erf2/ """ - def fdiff(self, argindex): x, y = self.args if argindex == 1: @@ -753,7 +751,6 @@ class erfinv(Function): .. [2] http://functions.wolfram.com/GammaBetaErf/InverseErf/ """ - def fdiff(self, argindex =1): if argindex == 1: return sqrt(S.Pi)*exp(self.func(self.args[0])**2)*S.Half @@ -831,7 +828,6 @@ class erfcinv (Function): .. [2] http://functions.wolfram.com/GammaBetaErf/InverseErfc/ """ - def fdiff(self, argindex =1): if argindex == 1: return -sqrt(S.Pi)*exp(self.func(self.args[0])**2)*S.Half @@ -908,7 +904,6 @@ class erf2inv(Function): .. [1] http://functions.wolfram.com/GammaBetaErf/InverseErf2/ """ - def fdiff(self, argindex): x, y = self.args if argindex == 1: @@ -1046,7 +1041,6 @@ class Ei(Function): """ - @classmethod def eval(cls, z): if not z.is_polar and z.is_negative: @@ -1204,7 +1198,6 @@ class expint(Function): """ - @classmethod def eval(cls, nu, z): from sympy import (unpolarify, expand_mul, uppergamma, exp, gamma, @@ -1388,7 +1381,6 @@ class li(Function): .. [4] http://mathworld.wolfram.com/SoldnersConstant.html """ - @classmethod def eval(cls, z): if z is S.Zero: @@ -1505,7 +1497,6 @@ class Li(Function): .. [3] http://dlmf.nist.gov/6 """ - @classmethod def eval(cls, z): if z is S.Infinity: @@ -1536,7 +1527,6 @@ def _eval_rewrite_as_tractable(self, z): class TrigonometricIntegral(Function): """ Base class for trigonometric integrals. """ - @classmethod def eval(cls, z): if z == 0: @@ -2330,7 +2320,6 @@ class _erfs(Function): tractable for the Gruntz algorithm. """ - def _eval_aseries(self, n, args0, x, logx): from sympy import Order point = args0[0] @@ -2375,7 +2364,6 @@ class _eis(Function): tractable for the Gruntz algorithm. """ - def _eval_aseries(self, n, args0, x, logx): from sympy import Order if args0[0] != S.Infinity: @@ -2387,7 +2375,6 @@ def _eval_aseries(self, n, args0, x, logx): # It is very inefficient to first add the order and then do the nseries return (Add(*l))._eval_nseries(x, n, logx) + o - def fdiff(self, argindex=1): if argindex == 1: z = self.args[0] diff --git a/sympy/functions/special/gamma_functions.py b/sympy/functions/special/gamma_functions.py index f44e2c44767..b6e5dfe3b82 100644 --- a/sympy/functions/special/gamma_functions.py +++ b/sympy/functions/special/gamma_functions.py @@ -252,7 +252,6 @@ class lowergamma(Function): .. [5] http://functions.wolfram.com/GammaBetaErf/Gamma3/ """ - def fdiff(self, argindex=2): from sympy import meijerg, unpolarify if argindex == 2: @@ -321,7 +320,7 @@ def _eval_evalf(self, prec): def _eval_conjugate(self): z = self.args[1] - if not z in (S.Zero, S.NegativeInfinity): + if z not in (S.Zero, S.NegativeInfinity): return self.func(self.args[0].conjugate(), z.conjugate()) def _eval_rewrite_as_uppergamma(self, s, x): @@ -397,7 +396,6 @@ class uppergamma(Function): .. [6] http://en.wikipedia.org/wiki/Exponential_integral#Relation_with_other_functions """ - def fdiff(self, argindex=2): from sympy import meijerg, unpolarify if argindex == 2: @@ -461,7 +459,7 @@ def eval(cls, a, z): def _eval_conjugate(self): z = self.args[1] - if not z in (S.Zero, S.NegativeInfinity): + if z not in (S.Zero, S.NegativeInfinity): return self.func(self.args[0].conjugate(), z.conjugate()) def _eval_rewrite_as_lowergamma(self, s, x): @@ -571,7 +569,6 @@ class polygamma(Function): .. [4] http://functions.wolfram.com/GammaBetaErf/PolyGamma2/ """ - def fdiff(self, argindex=2): if argindex == 2: n, z = self.args[:2] @@ -927,7 +924,7 @@ def _eval_is_extended_real(self): def _eval_conjugate(self): z = self.args[0] - if not z in (S.Zero, S.NegativeInfinity): + if z not in (S.Zero, S.NegativeInfinity): return self.func(z.conjugate()) def fdiff(self, argindex=1): diff --git a/sympy/functions/special/hyper.py b/sympy/functions/special/hyper.py index 2d57882f2f6..069427b18bb 100644 --- a/sympy/functions/special/hyper.py +++ b/sympy/functions/special/hyper.py @@ -176,7 +176,6 @@ class hyper(TupleParametersBase): .. [2] http://en.wikipedia.org/wiki/Generalized_hypergeometric_function """ - def __new__(cls, ap, bq, z): # TODO should we check convergence conditions? return Function.__new__(cls, _prep_tuple(ap), _prep_tuple(bq), z) @@ -434,7 +433,6 @@ class meijerg(TupleParametersBase): """ - def __new__(cls, *args): if len(args) == 5: args = [(args[0], args[1]), (args[2], args[3]), args[4]] @@ -706,7 +704,6 @@ class HyperRep(Function): supply the actual functions. """ - @classmethod def eval(cls, *args): from sympy import unpolarify diff --git a/sympy/functions/special/polynomials.py b/sympy/functions/special/polynomials.py index b47eb16a183..54a5051936d 100644 --- a/sympy/functions/special/polynomials.py +++ b/sympy/functions/special/polynomials.py @@ -715,7 +715,6 @@ class chebyshevu_root(Function): sympy.polys.orthopolys.laguerre_poly """ - @classmethod def eval(cls, n, k): if not ((0 <= k) and (k < n)): diff --git a/sympy/functions/special/tensor_functions.py b/sympy/functions/special/tensor_functions.py index 0150506e6c7..f3252ddb219 100644 --- a/sympy/functions/special/tensor_functions.py +++ b/sympy/functions/special/tensor_functions.py @@ -174,7 +174,7 @@ def eval(cls, i, j): def _eval_power(self, expt): if expt.is_positive: return self - if expt.is_negative and not -expt is S.One: + if expt.is_negative and -expt is not S.One: return 1/self @property diff --git a/sympy/functions/special/tests/test_error_functions.py b/sympy/functions/special/tests/test_error_functions.py index 1bba5305da0..f92e06cd575 100644 --- a/sympy/functions/special/tests/test_error_functions.py +++ b/sympy/functions/special/tests/test_error_functions.py @@ -81,7 +81,7 @@ def test_erf_series(): def test_erf_evalf(): - assert abs( erf(Float(2.0)) - 0.995322265 ) < 1E-8 # XXX + assert abs( erf(Float(2.0)) - 0.995322265 ) < 1E-8 # XXX def test__erfs(): @@ -144,7 +144,7 @@ def test_erfc_series(): def test_erfc_evalf(): - assert abs( erfc(Float(2.0)) - 0.00467773 ) < 1E-8 # XXX + assert abs( erfc(Float(2.0)) - 0.00467773 ) < 1E-8 # XXX def test_erfi(): diff --git a/sympy/functions/special/tests/test_hyper.py b/sympy/functions/special/tests/test_hyper.py index d7308ded9a1..30a66f01a4e 100644 --- a/sympy/functions/special/tests/test_hyper.py +++ b/sympy/functions/special/tests/test_hyper.py @@ -331,6 +331,6 @@ def test_limits(): hyper((1,), (S(4)/3, S(5)/3), 0) + \ 9*k**2*hyper((2,), (S(7)/3, S(8)/3), 0)/20 + \ 81*k**4*hyper((3,), (S(10)/3, S(11)/3), 0)/1120 + \ - O(k**6) # issue 6350 + O(k**6) # issue 6350 assert limit(meijerg((), (), (1,), (0,), -x), x, 0) == \ - meijerg(((), ()), ((1,), (0,)), 0) # issue 6052 + meijerg(((), ()), ((1,), (0,)), 0) # issue 6052 diff --git a/sympy/geometry/ellipse.py b/sympy/geometry/ellipse.py index dd374c09553..ba3862068e0 100644 --- a/sympy/geometry/ellipse.py +++ b/sympy/geometry/ellipse.py @@ -515,7 +515,6 @@ def rotate(self, angle=0, pt=None): # XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.') - def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since it is the major and minor axes which must be scaled and they are not GeometryEntities. @@ -847,7 +846,6 @@ def normal_lines(self, p, prec=None): slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes] return [Line(pt, slope=s) for pt,s in zip(points, slopes)] - def arbitrary_point(self, parameter='t'): """A parameterized point on the ellipse. @@ -1083,7 +1081,6 @@ def _do_ellipse_intersection(self, o): result = solve([seq, oeq], [x, y]) return [Point(*r) for r in list(uniq(result))] - def intersection(self, o): """The intersection of this ellipse and another geometrical entity `o`. diff --git a/sympy/geometry/entity.py b/sympy/geometry/entity.py index 2761e389a15..e2ec8c4f4da 100644 --- a/sympy/geometry/entity.py +++ b/sympy/geometry/entity.py @@ -339,7 +339,7 @@ def _eval_subs(self, old, new): else: old = Point(old) new = Point(new) - return self._subs(old, new) + return self._subs(old, new) def translate(x, y): """Return the matrix to translate a 2-D point by x and y.""" diff --git a/sympy/geometry/line.py b/sympy/geometry/line.py index 540684a99f6..72d477ce09d 100644 --- a/sympy/geometry/line.py +++ b/sympy/geometry/line.py @@ -1360,7 +1360,6 @@ def ydirection(self): else: return S.NegativeInfinity - def distance(self, o): """ Finds the shortest distance between the ray and a point. @@ -1396,7 +1395,6 @@ def distance(self, o): # the following applies when neither of the above apply return self.source.distance(o) - def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the Ray. Gives values that will produce a ray that is 10 units long (where a unit is diff --git a/sympy/geometry/line3d.py b/sympy/geometry/line3d.py index 88679b4a8fd..2278dada5b0 100644 --- a/sympy/geometry/line3d.py +++ b/sympy/geometry/line3d.py @@ -708,7 +708,7 @@ def intersection(self, o): if len(c) == 1 and len(d) == 1: return [] e = a.subs(t1, c[t1]) - if e in self and e in o: + if e in self and e in o: return [e] else: return [] diff --git a/sympy/geometry/plane.py b/sympy/geometry/plane.py index 41d3665adf5..9a5d988da4a 100644 --- a/sympy/geometry/plane.py +++ b/sympy/geometry/plane.py @@ -167,7 +167,6 @@ def projection(self, pt): return rv return self.intersection(Line3D(rv, rv + Point3D(self.normal_vector)))[0] - def projection_line(self, line): """Project the given line onto the plane through the normal plane containing the line. @@ -410,7 +409,6 @@ def angle_between(self, o): e = sqrt(sum([i**2 for i in o.normal_vector])) return acos(c/(d*e)) - @staticmethod def are_concurrent(*planes): """Is a sequence of Planes concurrent? diff --git a/sympy/geometry/tests/test_geometry.py b/sympy/geometry/tests/test_geometry.py index a4229e1252c..6e1973badbe 100644 --- a/sympy/geometry/tests/test_geometry.py +++ b/sympy/geometry/tests/test_geometry.py @@ -209,7 +209,6 @@ def test_point3D(): assert p3.intersection(Point3D(0, 0, 0)) == [p3] assert p3.intersection(p4) == [] - assert p4 * 5 == Point3D(5, 5, 5) assert p4 / 5 == Point3D(0.2, 0.2, 0.2) @@ -235,7 +234,6 @@ def test_point3D(): # Test __new__ assert Point3D(Point3D(1, 2, 3), 4, 5, evaluate=False) == Point3D(1, 2, 3) - # Test length property returns correctly assert p.length == 0 assert p1_1.length == 0 @@ -515,7 +513,6 @@ def test_line_geom(): r1 = Ray((2, 2), (3, 5)) assert r.contains(r1) is False - # Special cases of projection and intersection r1 = Ray(Point(1, 1), Point(2, 2)) r2 = Ray(Point(2, 2), Point(0, 0)) @@ -748,7 +745,6 @@ def test_line3d(): assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, 3, 1)) == \ sqrt(17)/2 - # Special cases of projection and intersection r1 = Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) r2 = Ray3D(Point3D(2, 2, 2), Point3D(0, 0, 0)) @@ -847,7 +843,6 @@ def test_plane(): Ray3D(Point3D(14/3, 11/3, 11/3), Point3D(13/3, 13/3, 10/3)) assert pl3.perpendicular_line(r.args) == pl3.perpendicular_line(r) - assert pl3.is_parallel(pl6) is False assert pl4.is_parallel(pl6) assert pl6.is_parallel(l1) is False @@ -1086,7 +1081,6 @@ def test_ellipse_geom(): assert e.normal_lines((x + 1, 0)) == [Line(Point(0, 0), Point(1, 0))] raises(NotImplementedError, lambda: e.normal_lines((x + 1, 1))) - # Properties major = 3 minor = 1 @@ -1232,7 +1226,6 @@ def test_polygon(): Point(15, -3), Point(15, 10), Point(15, 15)) == \ Polygon(Point(-15,-15), Point(15,-15), Point(15,15), Point(-15,15)) - p1 = Polygon( Point(0, 0), Point(3, -1), Point(6, 0), Point(4, 5), diff --git a/sympy/integrals/heurisch.py b/sympy/integrals/heurisch.py index 5e526ba848c..a774ab305aa 100644 --- a/sympy/integrals/heurisch.py +++ b/sympy/integrals/heurisch.py @@ -292,7 +292,7 @@ def heurisch(f, x, rewrite=False, hints=None, mappings=None, retries=3, if M is not None: if M[a].is_positive: terms.add(erfi(sqrt(M[a])*x)) - else: # M[a].is_negative or unknown + else: # M[a].is_negative or unknown terms.add(erf(sqrt(-M[a])*x)) M = g.args[0].match(a*x**2 + b*x + c) @@ -341,13 +341,12 @@ def heurisch(f, x, rewrite=False, hints=None, mappings=None, retries=3, # TODO: caching is significant factor for why permutations work at all. Change this. V = _symbols('x', len(terms)) - # sort mapping expressions from largest to smallest (last is always x). - mapping = list(reversed(list(zip(*ordered( # - [(a[0].as_independent(x)[1], a) for a in zip(terms, V)])))[1])) # - rev_mapping = {v: k for k, v in mapping} # - if mappings is None: # - # optimizing the number of permutations of mapping # + mapping = list(reversed(list(zip(*ordered( # + [(a[0].as_independent(x)[1], a) for a in zip(terms, V)])))[1])) # + rev_mapping = {v: k for k, v in mapping} # + if mappings is None: # + # optimizing the number of permutations of mapping # assert mapping[-1][0] == x # if not, find it and correct this comment unnecessary_permutations = [mapping.pop(-1)] mappings = permutations(mapping) @@ -526,9 +525,9 @@ def _integrate(field=None): def find_non_syms(expr): if expr.is_Integer or expr.is_Rational: - pass # ignore trivial numbers + pass # ignore trivial numbers elif expr in syms: - pass # ignore variables + pass # ignore variables elif not expr.has(*syms): non_syms.add(expr) elif expr.is_Add or expr.is_Mul or expr.is_Pow: diff --git a/sympy/integrals/integrals.py b/sympy/integrals/integrals.py index b02330f3421..5b96edf80f5 100644 --- a/sympy/integrals/integrals.py +++ b/sympy/integrals/integrals.py @@ -727,7 +727,6 @@ def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None, except (ValueError, PolynomialError): pass - # if it is a poly(x) then let the polynomial integrate itself (fast) # # It is important to make this check first, otherwise the other code diff --git a/sympy/integrals/manualintegrate.py b/sympy/integrals/manualintegrate.py index 4e0b9d8d8bd..08cfe0174a1 100644 --- a/sympy/integrals/manualintegrate.py +++ b/sympy/integrals/manualintegrate.py @@ -30,7 +30,8 @@ def Rule(name, props=""): # GOTCHA: namedtuple class name not considered! def __eq__(self, other): return self.__class__ == other.__class__ and tuple.__eq__(self, other) - __neq__ = lambda self, other: not __eq__(self, other) + def __neq__(self, other): + return not __eq__(self, other) cls = namedtuple(name, props + " context symbol") cls.__eq__ = __eq__ cls.__ne__ = __neq__ @@ -363,7 +364,6 @@ def pull_out_u_rl(integrand): pull_out_polys, pull_out_u(sympy.sin, sympy.cos), pull_out_u(sympy.exp)] - dummy = sympy.Dummy("temporary") # we can integrate log(x) and atan(x) by setting dv = 1 if isinstance(integrand, (sympy.log, sympy.atan, sympy.asin, sympy.acos)): diff --git a/sympy/integrals/rde.py b/sympy/integrals/rde.py index cd9b1e009f0..1d5dedaf166 100644 --- a/sympy/integrals/rde.py +++ b/sympy/integrals/rde.py @@ -666,7 +666,7 @@ def solve_poly_rde(b, cQ, n, DE, parametric=False): b0, c0 = b0.as_poly(DE.t), c0.as_poly(DE.t) if b0 is None: # See above comment raise ValueError("b0 should be a non-Null value") - if c0 is None: + if c0 is None: raise ValueError("c0 should be a non-Null value") y = solve_poly_rde(b0, c0, n, DE).as_poly(DE.t) return h + y diff --git a/sympy/integrals/risch.py b/sympy/integrals/risch.py index f9fa578dbc7..bd20b47be60 100644 --- a/sympy/integrals/risch.py +++ b/sympy/integrals/risch.py @@ -1057,7 +1057,7 @@ def laurent_series(a, d, F, n, DE): V.append(v) DE_D_list.append(Poly(Z[j + 1],Z[j])) - DE_new = DifferentialExtension(extension = {'D': DE_D_list}) #a differential indeterminate + DE_new = DifferentialExtension(extension = {'D': DE_D_list}) # a differential indeterminate for j in range(0, n): zEha = Poly(z**(n + j), DE.t)*E**(j + 1)*ha zEhd = hd diff --git a/sympy/integrals/tests/test_heurisch.py b/sympy/integrals/tests/test_heurisch.py index 3e3c337548b..fb8c91d3666 100644 --- a/sympy/integrals/tests/test_heurisch.py +++ b/sympy/integrals/tests/test_heurisch.py @@ -227,7 +227,7 @@ def test_pmint_trig(): assert heurisch(f, x) == g -@slow # 8 seconds on 3.4 GHz +@slow # 8 seconds on 3.4 GHz def test_pmint_logexp(): f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x g = log(x**2 + 2*x*exp(x) + 2*x*log(x) + exp(2*x) + 2*exp(x)*log(x) + log(x)**2)/2 + 1/(x + exp(x) + log(x)) @@ -237,7 +237,7 @@ def test_pmint_logexp(): assert ratsimp(heurisch(f, x)) == g -@slow # 8 seconds on 3.4 GHz +@slow # 8 seconds on 3.4 GHz def test_pmint_erf(): f = exp(-x**2)*erf(x)/(erf(x)**3 - erf(x)**2 - erf(x) + 1) g = sqrt(pi)*log(erf(x) - 1)/8 - sqrt(pi)*log(erf(x) + 1)/8 - sqrt(pi)/(4*erf(x) - 4) @@ -264,7 +264,7 @@ def test_pmint_besselj(): assert heurisch(f, x) == g -@slow # 110 seconds on 3.4 GHz +@slow # 110 seconds on 3.4 GHz def test_pmint_WrightOmega(): if ON_TRAVIS: skip("Too slow for travis.") diff --git a/sympy/integrals/tests/test_integrals.py b/sympy/integrals/tests/test_integrals.py index bad45a00956..2b8ffce748c 100644 --- a/sympy/integrals/tests/test_integrals.py +++ b/sympy/integrals/tests/test_integrals.py @@ -84,7 +84,7 @@ def test_basics(): assert diff_test(Integral(x, (x, 3*y))) == {y} assert diff_test(Integral(x, (a, 3*y))) == {x, y} - assert integrate(x, (x, oo, oo)) == 0 #issue 8171 + assert integrate(x, (x, oo, oo)) == 0 # issue 8171 assert integrate(x, (x, -oo, -oo)) == 0 # sum integral of terms @@ -738,7 +738,7 @@ def test_is_zero(): assert i.is_zero is None assert Integral(m, (x, 0), (m, 1, exp(x))).is_zero is True - assert Integral(x, (x, oo, oo)).is_zero # issue 8171 + assert Integral(x, (x, oo, oo)).is_zero # issue 8171 assert Integral(x, (x, -oo, -oo)).is_zero # this is zero but is beyond the scope of what is_zero diff --git a/sympy/integrals/tests/test_meijerint.py b/sympy/integrals/tests/test_meijerint.py index b7e9f4b4610..62fc73a38e9 100644 --- a/sympy/integrals/tests/test_meijerint.py +++ b/sympy/integrals/tests/test_meijerint.py @@ -12,7 +12,6 @@ from sympy.abc import x, y, a, b, c, d, s, t, z - def test_rewrite_single(): def t(expr, c, m): e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x) @@ -473,7 +472,8 @@ def E(expr): # inverse gaussian lamda, mu = symbols('lamda mu', positive=True) dist = sqrt(lamda/2/pi)*x**(-S(3)/2)*exp(-lamda*(x - mu)**2/x/2/mu**2) - mysimp = lambda expr: simplify(expr.rewrite(exp)) + def mysimp(expr): + return simplify(expr.rewrite(exp)) assert mysimp(integrate(dist, (x, 0, oo))) == 1 assert mysimp(integrate(x*dist, (x, 0, oo))) == mu assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda diff --git a/sympy/integrals/tests/test_risch.py b/sympy/integrals/tests/test_risch.py index 3258230ec16..e93cf58b748 100644 --- a/sympy/integrals/tests/test_risch.py +++ b/sympy/integrals/tests/test_risch.py @@ -638,7 +638,6 @@ def test_risch_integrate(): (x**4*exp(x**2) + 2*x**2*exp(x**2) + exp(x**2)), x) == \ NonElementaryIntegral(exp(-x**2), x) + exp(x**2)/(1 + x**2) - assert risch_integrate(0, x) == 0 # These are tested here in addition to in test_DifferentialExtension above diff --git a/sympy/integrals/transforms.py b/sympy/integrals/transforms.py index a4fb7fdba59..e1218b03157 100644 --- a/sympy/integrals/transforms.py +++ b/sympy/integrals/transforms.py @@ -1470,7 +1470,6 @@ def b(self): raise NotImplementedError( "Class %s must implement b(self) but does not" % self.__class__) - def _compute_transform(self, f, x, k, **hints): return _sine_cosine_transform(f, x, k, self.a(), self.b(), diff --git a/sympy/interactive/printing.py b/sympy/interactive/printing.py index 00a692a0093..8162be49eab 100644 --- a/sympy/interactive/printing.py +++ b/sympy/interactive/printing.py @@ -298,13 +298,14 @@ def init_printing(pretty_print=True, order=None, use_unicode=None, _stringify_func = stringify_func if pretty_print: - stringify_func = lambda expr: \ - _stringify_func(expr, order=order, - use_unicode=use_unicode, - wrap_line=wrap_line, - num_columns=num_columns) + def stringify_func(expr): + return _stringify_func(expr, order=order, + use_unicode=use_unicode, + wrap_line=wrap_line, + num_columns=num_columns) else: - stringify_func = lambda expr: _stringify_func(expr, order=order) + def stringify_func(expr): + return _stringify_func(expr, order=order) if in_ipython: _init_ipython_printing(ip, stringify_func, use_latex, diff --git a/sympy/liealgebras/root_system.py b/sympy/liealgebras/root_system.py index ecf1f03ec9b..aed3c5e9a7a 100644 --- a/sympy/liealgebras/root_system.py +++ b/sympy/liealgebras/root_system.py @@ -72,7 +72,6 @@ def simple_roots(self): roots[i] = root return roots - def all_roots(self): """Generate all the roots of a given root system. @@ -171,7 +170,6 @@ def add_as_roots(self, root1, root2): else: return "The sum of these two roots is not a root" - def cartan_matrix(self): """Cartan matrix of Lie algebra associated with this root system. diff --git a/sympy/liealgebras/tests/test_type_D.py b/sympy/liealgebras/tests/test_type_D.py index f8779ba3919..75f5502e691 100644 --- a/sympy/liealgebras/tests/test_type_D.py +++ b/sympy/liealgebras/tests/test_type_D.py @@ -2,7 +2,6 @@ from sympy.matrices import Matrix - def test_type_D(): c = CartanType("D4") m = Matrix(4, 4, [2, -1, 0, 0, -1, 2, -1, -1, 0, -1, 2, 0, 0, -1, 0 , 2]) diff --git a/sympy/liealgebras/type_a.py b/sympy/liealgebras/type_a.py index 37aaa0c052c..94f541551a8 100644 --- a/sympy/liealgebras/type_a.py +++ b/sympy/liealgebras/type_a.py @@ -17,7 +17,6 @@ def __new__(cls, n): raise ValueError("n can not be less than 1") return Standard_Cartan.__new__(cls, "A", n) - def dimension(self): """Dimension of the vector space V underlying the Lie algebra. @@ -31,7 +30,6 @@ def dimension(self): """ return self.n+1 - def basic_root(self, i, j): """ This is a method just to generate roots diff --git a/sympy/liealgebras/type_c.py b/sympy/liealgebras/type_c.py index edc413b43ec..90f13904968 100644 --- a/sympy/liealgebras/type_c.py +++ b/sympy/liealgebras/type_c.py @@ -9,7 +9,6 @@ def __new__(cls, n): raise ValueError("n can not be less than 3") return Standard_Cartan.__new__(cls, "C", n) - def dimension(self): """Dimension of the vector space V underlying the Lie algebra. @@ -69,7 +68,6 @@ def simple_root(self, i): root[n-1] = 2 return root - def positive_roots(self): """Generates all the positive roots of A_n. @@ -148,7 +146,6 @@ def cartan_matrix(self): m[n-1, n-2] = -2 return m - def basis(self): """ Returns the number of independent generators of C_n diff --git a/sympy/liealgebras/type_d.py b/sympy/liealgebras/type_d.py index 7a89f3e3325..b54373e98da 100644 --- a/sympy/liealgebras/type_d.py +++ b/sympy/liealgebras/type_d.py @@ -9,7 +9,6 @@ def __new__(cls, n): raise ValueError("n cannot be less than 3") return Standard_Cartan.__new__(cls, "D", n) - def dimension(self): """Dmension of the vector space V underlying the Lie algebra. @@ -76,7 +75,6 @@ def simple_root(self, i): root[n-1] = 1 return root - def positive_roots(self): """ This method generates all the positive roots of diff --git a/sympy/liealgebras/type_e.py b/sympy/liealgebras/type_e.py index 16dd6cf4ede..fd962917964 100644 --- a/sympy/liealgebras/type_e.py +++ b/sympy/liealgebras/type_e.py @@ -212,8 +212,6 @@ def positive_roots(self): return posroots - - def roots(self): """ Returns the total number of roots of E_n @@ -227,7 +225,6 @@ def roots(self): if n == 8: return 240 - def cartan_matrix(self): """ Returns the Cartan matrix for G_2 @@ -247,8 +244,6 @@ def cartan_matrix(self): [-1, 2, -1, 0], [ 0, -1, 2, -1], [ 0, 0, -1, 2]]) - - """ n = self.n @@ -264,7 +259,6 @@ def cartan_matrix(self): m[n-1, n-2] = -1 return m - def basis(self): """ Returns the number of independent generators of E_n diff --git a/sympy/liealgebras/type_f.py b/sympy/liealgebras/type_f.py index a24244a6301..afc2265f8c3 100644 --- a/sympy/liealgebras/type_f.py +++ b/sympy/liealgebras/type_f.py @@ -25,7 +25,6 @@ def dimension(self): return 4 - def basic_root(self, i, j): """Generate roots with 1 in ith position and -1 in jth postion. @@ -120,7 +119,6 @@ def positive_roots(self): return posroots - def roots(self): """ Returns the total number of roots for F_4 diff --git a/sympy/liealgebras/type_g.py b/sympy/liealgebras/type_g.py index 203f214dffa..7332a7dcc4d 100644 --- a/sympy/liealgebras/type_g.py +++ b/sympy/liealgebras/type_g.py @@ -10,7 +10,6 @@ def __new__(cls, n): raise ValueError("n should be 2") return Standard_Cartan.__new__(cls, "G", 2) - def dimension(self): """Dimension of the vector space V underlying the Lie algebra. diff --git a/sympy/liealgebras/weyl_group.py b/sympy/liealgebras/weyl_group.py index c9a684d655d..6e3b98f8815 100644 --- a/sympy/liealgebras/weyl_group.py +++ b/sympy/liealgebras/weyl_group.py @@ -180,7 +180,6 @@ def element_order(self, weylelt): order = lcm / m return order - if self.cartan_type.series == 'F': a = self.matrix_form(weylelt) order = 1 @@ -189,7 +188,6 @@ def element_order(self, weylelt): order += 1 return order - if self.cartan_type.series == "B" or self.cartan_type.series == "C": a = self.matrix_form(weylelt) order = 1 @@ -213,10 +211,8 @@ def delete_doubles(self, reflections): del copy[counter] counter += 1 - return copy - def matrix_form(self, weylelt): """ This method takes input from the user in the form of products of the @@ -347,7 +343,6 @@ def matrix_form(self, weylelt): matrixform *= mat return matrixform - if self.cartan_type.series == 'B' or self.cartan_type.series == 'C': matrixform = eye(n) for elt in reflections: @@ -364,8 +359,6 @@ def matrix_form(self, weylelt): matrixform *= mat return matrixform - - def coxeter_diagram(self): """ This method returns the Coxeter diagram corresponding to a Weyl group. diff --git a/sympy/logic/boolalg.py b/sympy/logic/boolalg.py index 19a4aa23623..6782368dbf0 100644 --- a/sympy/logic/boolalg.py +++ b/sympy/logic/boolalg.py @@ -827,7 +827,7 @@ def __new__(cls, *args, **options): argset = set(args) for x in args: - if isinstance(x, Number) or x in [True, False]: # Includes 0, 1 + if isinstance(x, Number) or x in [True, False]: # Includes 0, 1 argset.discard(x) argset.add(True if x else False) rel = [] diff --git a/sympy/logic/tests/test_boolalg.py b/sympy/logic/tests/test_boolalg.py index 628cb5f2414..de99978ce68 100644 --- a/sympy/logic/tests/test_boolalg.py +++ b/sympy/logic/tests/test_boolalg.py @@ -553,9 +553,9 @@ def test_true_false(): if not (T is True and F is False): assert T & F is false assert F & T is false - if not F is False: + if F is not False: assert F & F is false - if not T is True: + if T is not True: assert T & T is true assert Or(T, F) is true @@ -567,9 +567,9 @@ def test_true_false(): if not (T is True and F is False): assert T | F is true assert F | T is true - if not F is False: + if F is not False: assert F | F is false - if not T is True: + if T is not True: assert T | T is true assert Xor(T, F) is true @@ -581,9 +581,9 @@ def test_true_false(): if not (T is True and F is False): assert T ^ F is true assert F ^ T is true - if not F is False: + if F is not False: assert F ^ F is false - if not T is True: + if T is not True: assert T ^ T is false assert Nand(T, F) is true @@ -613,10 +613,10 @@ def test_true_false(): assert F << T is false assert F >> T is true assert T << F is true - if not F is False: + if F is not False: assert F >> F is true assert F << F is true - if not T is True: + if T is not True: assert T >> T is true assert T << T is true diff --git a/sympy/matrices/dense.py b/sympy/matrices/dense.py index 32a42e04abe..67a0aeb64ef 100644 --- a/sympy/matrices/dense.py +++ b/sympy/matrices/dense.py @@ -1565,9 +1565,11 @@ def casoratian(seqs, n, zero=True): seqs = list(map(sympify, seqs)) if not zero: - f = lambda i, j: seqs[j].subs(n, n + i) + def f(i, j): + return seqs[j].subs(n, n + i) else: - f = lambda i, j: seqs[j].subs(n, i) + def f(i, j): + return seqs[j].subs(n, i) k = len(seqs) diff --git a/sympy/matrices/expressions/blockmatrix.py b/sympy/matrices/expressions/blockmatrix.py index 20c7183ec67..ad672238cf6 100644 --- a/sympy/matrices/expressions/blockmatrix.py +++ b/sympy/matrices/expressions/blockmatrix.py @@ -275,7 +275,8 @@ def block_collapse(expr): >>> print(block_collapse(C*B)) Matrix([[X, Z*Y + Z]]) """ - hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix) + def hasbm(expr): + return isinstance(expr, MatrixExpr) and expr.has(BlockMatrix) rule = exhaust( bottom_up(exhaust(condition(hasbm, typed( {MatAdd: do_one(bc_matadd, bc_block_plus_ident), @@ -383,7 +384,8 @@ def deblock(B): """ Flatten a BlockMatrix of BlockMatrices """ if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix): return B - wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]]) + def wrap(x): + return x if isinstance(x, BlockMatrix) else BlockMatrix([[x]]) bb = B.blocks.applyfunc(wrap) # everything is a block from sympy import Matrix @@ -400,7 +402,6 @@ def deblock(B): return B - def reblock_2x2(B): """ Reblock a BlockMatrix so that it has 2x2 blocks of block matrices """ if not isinstance(B, BlockMatrix) or not all(d > 2 for d in B.blocks.shape): diff --git a/sympy/matrices/expressions/factorizations.py b/sympy/matrices/expressions/factorizations.py index fd4a8221c84..1dd03ae2488 100644 --- a/sympy/matrices/expressions/factorizations.py +++ b/sympy/matrices/expressions/factorizations.py @@ -12,8 +12,10 @@ class LofLU(Factorization): class UofLU(Factorization): predicates = Q.upper_triangular, -class LofCholesky(LofLU): pass -class UofCholesky(UofLU): pass +class LofCholesky(LofLU): + pass +class UofCholesky(UofLU): + pass class QofQR(Factorization): predicates = Q.orthogonal, diff --git a/sympy/matrices/expressions/matadd.py b/sympy/matrices/expressions/matadd.py index 59d606fccc4..c85909ddbd7 100644 --- a/sympy/matrices/expressions/matadd.py +++ b/sympy/matrices/expressions/matadd.py @@ -70,8 +70,10 @@ def validate(*args): if A.shape != B.shape: raise ShapeError("Matrices %s and %s are not aligned"%(A, B)) -factor_of = lambda arg: arg.as_coeff_mmul()[0] -matrix_of = lambda arg: unpack(arg.as_coeff_mmul()[1]) +def factor_of(arg): + return arg.as_coeff_mmul()[0] +def matrix_of(arg): + return unpack(arg.as_coeff_mmul()[1]) def combine(cnt, mat): if cnt == 1: return mat diff --git a/sympy/matrices/expressions/matexpr.py b/sympy/matrices/expressions/matexpr.py index ea3c80ab1ab..8cf2c960ab0 100644 --- a/sympy/matrices/expressions/matexpr.py +++ b/sympy/matrices/expressions/matexpr.py @@ -63,7 +63,6 @@ class MatrixExpr(Basic): is_commutative = False - def __new__(cls, *args, **kwargs): args = map(sympify, args) return Basic.__new__(cls, *args, **kwargs) @@ -457,7 +456,6 @@ def __new__(cls, m, n): def shape(self): return (self.args[0], self.args[1]) - @_sympifyit('other', NotImplemented) @call_highest_priority('__rpow__') def __pow__(self, other): diff --git a/sympy/matrices/expressions/matpow.py b/sympy/matrices/expressions/matpow.py index c03f8cff006..21268cf2913 100644 --- a/sympy/matrices/expressions/matpow.py +++ b/sympy/matrices/expressions/matpow.py @@ -47,7 +47,6 @@ def _entry(self, i, j): + " of matrix power either not defined or not implemented") return A._entry(i, j) - def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: diff --git a/sympy/matrices/expressions/slice.py b/sympy/matrices/expressions/slice.py index 33e209f4fb0..b211992da9b 100644 --- a/sympy/matrices/expressions/slice.py +++ b/sympy/matrices/expressions/slice.py @@ -1,6 +1,6 @@ from __future__ import print_function, division -from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions.matexpr import MatrixExpr from sympy import Tuple, Basic from sympy.functions.elementary.integers import floor @@ -16,7 +16,7 @@ def normalize(i, parentsize): i.append(1) start, stop, step = i start = start or 0 - if stop == None: + if stop is None: stop = parentsize if (start < 0) == True: start += parentsize diff --git a/sympy/matrices/expressions/tests/test_hadamard.py b/sympy/matrices/expressions/tests/test_hadamard.py index 2f14fe175de..4aa27c430a2 100644 --- a/sympy/matrices/expressions/tests/test_hadamard.py +++ b/sympy/matrices/expressions/tests/test_hadamard.py @@ -14,8 +14,8 @@ def test_HadamardProduct(): assert HadamardProduct(A, B, A).shape == A.shape raises(ShapeError, lambda: HadamardProduct(A, B.T)) - raises(TypeError, lambda: HadamardProduct(A, n)) - raises(TypeError, lambda: HadamardProduct(A, 1)) + raises(TypeError, lambda: HadamardProduct(A, n)) + raises(TypeError, lambda: HadamardProduct(A, 1)) assert HadamardProduct(A, 2*B, -A)[1, 1] == \ -2 * A[1, 1] * B[1, 1] * A[1, 1] @@ -40,7 +40,7 @@ def test_canonicalize(): X = MatrixSymbol('X', 2, 2) expr = HadamardProduct(X, check=False) assert isinstance(expr, HadamardProduct) - expr2 = expr.doit() # unpack is called + expr2 = expr.doit() # unpack is called assert isinstance(expr2, MatrixSymbol) def test_hadamard(): diff --git a/sympy/matrices/expressions/tests/test_matpow.py b/sympy/matrices/expressions/tests/test_matpow.py index 317e968e3ae..5db7b1a9ae5 100644 --- a/sympy/matrices/expressions/tests/test_matpow.py +++ b/sympy/matrices/expressions/tests/test_matpow.py @@ -42,7 +42,7 @@ def test_as_explicit(): assert MatPow(A, -1).as_explicit() == A.inv() assert MatPow(A, -2).as_explicit() == (A.inv())**2 # less expensive than testing on a 2x2 - A = ImmutableMatrix([4]); + A = ImmutableMatrix([4]) assert MatPow(A, S.Half).as_explicit() == A**S.Half diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py index 144a23ff39f..a28ff6b615b 100644 --- a/sympy/matrices/matrices.py +++ b/sympy/matrices/matrices.py @@ -82,7 +82,7 @@ class MatrixBase(object): _class_priority = 3 _sympify = staticmethod(sympify) - __hash__ = None # Mutable + __hash__ = None # Mutable @classmethod def _handle_creation_inputs(cls, *args, **kwargs): @@ -215,7 +215,6 @@ def _handle_creation_inputs(cls, *args, **kwargs): raise ValueError('List length should be equal to rows*columns') flat_list = [cls._sympify(i) for i in flat_list] - # Matrix() elif len(args) == 0: # Empty Matrix @@ -1777,11 +1776,11 @@ def norm(self, ord=None): >>> v.norm(10) (sin(x)**10 + cos(x)**10)**(1/10) >>> A = Matrix([[1, 1], [1, 1]]) - >>> A.norm(2)# Spectral norm (max of |Ax|/|x| under 2-vector-norm) + >>> A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm) 2 - >>> A.norm(-2) # Inverse spectral norm (smallest singular value) + >>> A.norm(-2) # Inverse spectral norm (smallest singular value) 0 - >>> A.norm() # Frobenius Norm + >>> A.norm() # Frobenius Norm 2 >>> Matrix([1, -2]).norm(oo) 2 @@ -2003,7 +2002,7 @@ def is_zero(self): """ if any(i.is_zero == False for i in self): return False - if any(i.is_zero == None for i in self): + if any(i.is_zero is None for i in self): return None return True @@ -2782,13 +2781,13 @@ def berkowitz(self): >>> p, q, r = M.berkowitz() - >>> p # 1 x 1 M's sub-matrix + >>> p # 1 x 1 M's sub-matrix (1, -x) - >>> q # 2 x 2 M's sub-matrix + >>> q # 2 x 2 M's sub-matrix (1, -x, -y) - >>> r # 3 x 3 M's sub-matrix + >>> r # 3 x 3 M's sub-matrix (1, -2*x, x**2 - y*z - y, x*y - z**2) For more information on the implemented algorithm refer to: @@ -3072,7 +3071,8 @@ def condition_number(self): def __getattr__(self, attr): if attr in ('diff', 'integrate', 'limit'): def doit(*args): - item_doit = lambda item: getattr(item, attr)(*args) + def item_doit(item): + return getattr(item, attr)(*args) return self.applyfunc(item_doit) return doit else: @@ -4127,7 +4127,7 @@ def classof(A, B): >>> from sympy import Matrix, ImmutableMatrix >>> from sympy.matrices.matrices import classof - >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix + >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix >>> IM = ImmutableMatrix([[1, 2], [3, 4]]) >>> classof(M, IM) @@ -4183,7 +4183,7 @@ def mgamma(mu, lower=False): .. [1] http://en.wikipedia.org/wiki/Gamma_matrices """ from sympy import Matrix - if not mu in [0, 1, 2, 3, 5]: + if mu not in [0, 1, 2, 3, 5]: raise IndexError("Invalid Dirac index") if mu == 0: mat = ( diff --git a/sympy/matrices/tests/test_densearith.py b/sympy/matrices/tests/test_densearith.py index 9f76f3dde0a..2993e992b2b 100644 --- a/sympy/matrices/tests/test_densearith.py +++ b/sympy/matrices/tests/test_densearith.py @@ -39,7 +39,6 @@ def test_mulmatmat(): assert mulmatmat(b, d, ZZ) == [[ZZ(20)], [ZZ(98)]] - def test_mulmatscaler(): a = eye(3, ZZ) b = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]] diff --git a/sympy/matrices/tests/test_matrices.py b/sympy/matrices/tests/test_matrices.py index 7490f7beef9..5372717d0a2 100644 --- a/sympy/matrices/tests/test_matrices.py +++ b/sympy/matrices/tests/test_matrices.py @@ -990,7 +990,7 @@ def test_col_row_op(): def test_zip_row_op(): - for cls in classes[:2]: # XXX: immutable matrices don't support row ops + for cls in classes[:2]: # XXX: immutable matrices don't support row ops M = cls.eye(3) M.zip_row_op(1, 0, lambda v, u: v + 2*u) assert M == cls([[1, 0, 0], @@ -999,7 +999,7 @@ def test_zip_row_op(): M = cls.eye(3)*2 M[0, 1] = -1 - M.zip_row_op(1, 0, lambda v, u: v + 2*u); M + M.zip_row_op(1, 0, lambda v, u: v + 2*u) assert M == cls([[2, -1, 0], [4, 0, 0], [0, 0, 2]]) @@ -1541,8 +1541,8 @@ def test_jordan_form_complex_issue_9274(): [-4, 2, 0, 1], [ 0, 0, 2, 4], [ 0, 0, -4, 2]]) - p = 2 - 4*I; - q = 2 + 4*I; + p = 2 - 4*I + q = 2 + 4*I Jmust1 = Matrix([[p, 1, 0, 0], [0, p, 0, 0], [0, 0, q, 1], @@ -2011,10 +2011,10 @@ def test_is_zero(): assert Matrix([[0, 0], [0, 0]]).is_zero assert zeros(3, 4).is_zero assert not eye(3).is_zero - assert Matrix([[x, 0], [0, 0]]).is_zero == None - assert SparseMatrix([[x, 0], [0, 0]]).is_zero == None - assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero == None - assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero == None + assert Matrix([[x, 0], [0, 0]]).is_zero is None + assert SparseMatrix([[x, 0], [0, 0]]).is_zero is None + assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero is None + assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero is None assert Matrix([[x, 1], [0, 0]]).is_zero == False a = Symbol('a', nonzero=True) assert Matrix([[a, 0], [0, 0]]).is_zero == False diff --git a/sympy/ntheory/bbp_pi.py b/sympy/ntheory/bbp_pi.py deleted file mode 100644 index 993360675a7..00000000000 --- a/sympy/ntheory/bbp_pi.py +++ /dev/null @@ -1,110 +0,0 @@ -''' -This implementation is a heavily modified fixed point implementation of -BBP_formula for calculating the nth position of pi. The original hosted -at: http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python) - -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sub-license, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Modifications: -1.Once the nth digit is selected the number of digits of working -precision is calculated to ensure that the 14 Hexadecimal representation -of that region is accurate. This was found empirically to be -int((math.log10(n//1000))+18). This was found by searching for a value -of working precision for the n = 0 and n = 1 then n was increased until -the result was less precise, therefore increased again this was repeated -for increasing n and an effective fit was found between n and the -working precision value. - -2. The while loop to evaluate whether the series has converged has be -replaced with a fixed for loop, that option was selected because in a -very large number of cases the loop converged to a point where no -difference can be detected in less than 15 iterations. (done for more -accurate memory and time banking). - -3. output hex string constrained to 14 characters (accuracy assured to be -n = 10**7) - -4. pi_hex_digits(n) changed to have coefficient to the formula in an -array (perhaps just a matter of preference). - -''' -from __future__ import print_function, division - -import math -from sympy.core.compatibility import range - - -def _series(j, n): - - # Left sum from the bbp algorithm - s = 0 - D = _dn(n) - for k in range(n + 1): - r = 8*k + j - s += (pow(16, n - k, r) << 4 * D) // r - - # Right sum. should iterate to infinty, but now just iterates to the point where - # one iterations change is beyond the resolution of the data type used - - t = 0 - for k in range(n + 1, n + 15): - xp = int(16**(n - k) * 16**D) - t += xp // (8 * k + j) - total = s + t - - return total - - -def pi_hex_digits(n): - """Returns a string containing 14 digits after the nth value of pi in hex - The decimal has been taken out of the number, so - n = 0[0] = 3 # First digit of pi in hex, 3 - - Examples - ======== - - >>> from sympy.ntheory.bbp_pi import pi_hex_digits - >>> pi_hex_digits(0) - '3243f6a8885a30' - >>> pi_hex_digits(10) - '5a308d313198a2' - """ - - # main of implementation arrays holding formulae coefficients - n -= 1 - a = [4, 2, 1, 1] - j = [1, 4, 5, 6] - - #formulae - x = + (a[0]*_series(j[0], n) - - a[1]*_series(j[1], n) - - a[2]*_series(j[2], n) - - a[3]*_series(j[3], n)) & (16**(_dn(n)) - 1) - - s = ("%014x" % x) - #s is constrained between 0 and 14 - return s[:14] - - -def _dn(n): - # controller for n dependence on precision - if (n < 1000): - return 16 - return int(math.log10(n//1000) + 18) diff --git a/sympy/ntheory/continued_fraction.py b/sympy/ntheory/continued_fraction.py index dd94a59f10a..d53a7ed60c0 100644 --- a/sympy/ntheory/continued_fraction.py +++ b/sympy/ntheory/continued_fraction.py @@ -2,16 +2,19 @@ def continued_fraction_periodic(p, q, d=0): - r""" - Find the periodic continued fraction expansion of a quadratic irrational. + r"""Find the periodic continued fraction [1]_ expansion. Compute the continued fraction expansion of a rational or a - quadratic irrational number, i.e. `\frac{p + \sqrt{d}}{q}`, where - `p`, `q` and `d \ge 0` are integers. + quadratic surd, i.e. `\frac{p + \sqrt{d}}{q}`, where `p`, `q` + and `d \ge 0` are integers. - Returns the continued fraction representation (canonical form) as - a list of integers, optionally ending (for quadratic irrationals) - with repeating block as the last term of this list. + Returns + ======= + + list + the continued fraction representation (canonical form) as a list of + integers, optionally ending (for quadratic irrationals) with + repeating block as the last term of this list. Parameters ========== @@ -54,7 +57,6 @@ def continued_fraction_periodic(p, q, d=0): .. [1] http://en.wikipedia.org/wiki/Periodic_continued_fraction .. [2] K. Rosen. Elementary Number theory and its applications. Addison-Wesley, 3 Sub edition, pages 379-381, January 1992. - """ from sympy.core.compatibility import as_int from sympy.functions import sqrt @@ -92,8 +94,7 @@ def continued_fraction_periodic(p, q, d=0): def continued_fraction_reduce(cf): - """ - Reduce a continued fraction to a rational or quadratic irrational. + """Reduce a continued fraction to a rational or quadratic irrational. Compute the rational or quadratic irrational number from its terminating or periodic continued fraction expansion. The @@ -132,7 +133,6 @@ def continued_fraction_reduce(cf): ======== continued_fraction_periodic - """ from sympy.core.symbol import Dummy from sympy.solvers import solve @@ -163,8 +163,7 @@ def untillist(cf): def continued_fraction_iterator(x): - """ - Return continued fraction expansion of x as iterator. + """Return continued fraction expansion of x as iterator. Examples ======== @@ -208,8 +207,7 @@ def continued_fraction_iterator(x): def continued_fraction_convergents(cf): - """ - Return an iterator over the convergents of a continued fraction (cf). + """Return an iterator over the convergents of a continued fraction. The parameter should be an iterable returning successive partial quotients of the continued fraction, such as might be @@ -247,7 +245,6 @@ def continued_fraction_convergents(cf): ======== continued_fraction_iterator - """ p_2, q_2 = Integer(0), Integer(1) p_1, q_1 = Integer(1), Integer(0) diff --git a/sympy/ntheory/egyptian_fraction.py b/sympy/ntheory/egyptian_fraction.py index fd6f58cd8d5..12d2db71a8e 100644 --- a/sympy/ntheory/egyptian_fraction.py +++ b/sympy/ntheory/egyptian_fraction.py @@ -7,9 +7,14 @@ def egyptian_fraction(r, algorithm="Greedy"): - """ - Return the list of denominators of an Egyptian fraction - expansion [1]_ of the said rational `r`. + """Compute an Egyptian fraction of the rational `r`. + + Returns + ======= + + list + The list of denominators of an Egyptian + fraction expansion [1]_. Parameters ========== @@ -101,7 +106,6 @@ def egyptian_fraction(r, algorithm="Greedy"): .. [2] https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions .. [3] http://www.ics.uci.edu/~eppstein/numth/egypt/conflict.html .. [4] http://ami.ektf.hu/uploads/papers/finalpdf/AMI_42_from129to134.pdf - """ if r <= 0: diff --git a/sympy/ntheory/factor_.py b/sympy/ntheory/factor_.py index d358f22271f..17b34555c82 100644 --- a/sympy/ntheory/factor_.py +++ b/sympy/ntheory/factor_.py @@ -23,8 +23,7 @@ def smoothness(n): - """ - Return the B-smooth and B-power smooth values of n. + """Return the B-smooth and B-power smooth values of n. The smoothness of n is the largest prime factor of n; the power- smoothness is the largest divisor raised to its multiplicity. @@ -192,8 +191,7 @@ def trailing(n): def multiplicity(p, n): - """ - Find the greatest integer m such that p**m divides n. + """Find the greatest integer m such that p**m divides n. Examples ======== @@ -204,7 +202,6 @@ def multiplicity(p, n): [0, 1, 2, 3, 3] >>> multiplicity(3, R(1, 9)) -2 - """ try: p, n = as_int(p), as_int(n) @@ -447,9 +444,8 @@ def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None): References ========== - - Richard Crandall & Carl Pomerance (2005), "Prime Numbers: - A Computational Perspective", Springer, 2nd edition, 229-231 - + .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: + A Computational Perspective", Springer, 2nd edition, 229-231 """ n = int(n) if n < 5: @@ -459,7 +455,8 @@ def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None): for i in range(retries + 1): U = V if not F: - F = lambda x: (pow(x, 2, n) + a) % n + def F(x): + return (pow(x, 2, n) + a) % n j = 0 while 1: if max_steps and (j > max_steps): @@ -711,7 +708,6 @@ def _factorint_small(factors, n, limit, fail_max): If factors of n were found they will be in the factors dictionary as {factor: multiplicity} and the returned value of n will have had those factors removed. The factors dictionary is modified in-place. - """ def done(n, d): @@ -939,7 +935,6 @@ def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, ======== smoothness, smoothness_p, divisors - """ factordict = {} if visual and not isinstance(n, Mul) and not isinstance(n, dict): @@ -1232,9 +1227,10 @@ def rec_gen(n=0): def divisors(n, generator=False): - r""" - Return all divisors of n sorted from 1..n by default. - If generator is True an unordered generator is returned. + r"""Return all divisors of n. + + Divisors are sorted from 1..n by default. If generator is True an + unordered generator is returned. The number of divisors of n can be quite large if there are many prime factors (counting repeated factors). If only the number of @@ -1252,13 +1248,15 @@ def divisors(n, generator=False): >>> list(divisors(120, generator=True)) [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120] - This is a slightly modified version of Tim Peters referenced at: - http://stackoverflow.com/questions/1010381/python-factorization - See Also ======== primefactors, factorint, divisor_count + + References + ========== + + .. [1] http://stackoverflow.com/questions/1010381/python-factorization """ n = as_int(abs(n)) @@ -1275,14 +1273,15 @@ def divisors(n, generator=False): def divisor_count(n, modulus=1): - """ - Return the number of divisors of ``n``. If ``modulus`` is not 1 then only - those that are divisible by ``modulus`` are counted. + """Return the number of divisors of ``n``. + + If ``modulus`` is not 1 then only those that are divisible by + ``modulus`` are counted. References ========== - - http://www.mayer.dial.pipex.com/maths/formulae.htm + .. [1] http://www.mayer.dial.pipex.com/maths/formulae.htm >>> from sympy import divisor_count >>> divisor_count(6) @@ -1321,8 +1320,7 @@ def _antidivisors(n): def antidivisors(n, generator=False): - r""" - Return all antidivisors of n sorted from 1..n by default. + r"""Return all antidivisors of n sorted from 1..n by default. Antidivisors [1]_ of n are numbers that do not divide n by the largest possible margin. If generator is True an unordered generator is returned. @@ -1358,8 +1356,7 @@ def antidivisors(n, generator=False): def antidivisor_count(n): - """ - Return the number of antidivisors [1]_ of ``n``. + """Return the number of antidivisors [1]_ of ``n``. References ========== @@ -1389,8 +1386,7 @@ def antidivisor_count(n): class totient(Function): - """ - Calculate the Euler totient function phi(n) + """Calculate the Euler totient function phi(n) >>> from sympy.ntheory import totient >>> totient(1) @@ -1420,8 +1416,7 @@ def _eval_is_integer(self): class divisor_sigma(Function): - """ - Calculate the divisor function `\sigma_k(n)` for positive integer n + r"""Calculate the divisor function `\sigma_k(n)` for positive integer n. ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])`` @@ -1486,8 +1481,7 @@ def eval(cls, n, k=1): def core(n, t=2): - """ - Calculate core(n,t) = `core_t(n)` of a positive integer n + """Calculate core(n,t) = `core_t(n)` of a positive integer n. ``core_2(n)`` is equal to the squarefree part of n diff --git a/sympy/ntheory/multinomial.py b/sympy/ntheory/multinomial.py index a2730c9c5b2..90c45b829a8 100644 --- a/sympy/ntheory/multinomial.py +++ b/sympy/ntheory/multinomial.py @@ -5,8 +5,9 @@ def binomial_coefficients(n): - """Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where - :math:`C_kn` are binomial coefficients and :math:`n=k1+k2`. + """Return a dictionary containing pairs `{(k1,k2) : C_{kn}}` where + `C_{kn}` are binomial coefficients and :math:`n=k1+k2`. + Examples ======== @@ -30,8 +31,7 @@ def binomial_coefficients(n): def binomial_coefficients_list(n): - """ Return a list of binomial coefficients as rows of the Pascal's - triangle. + """Return a list of binomial coefficients as rows of the Pascal's triangle. Examples ======== @@ -58,28 +58,32 @@ def multinomial_coefficients0(m, n, _tuple=tuple, _zip=zip): where ``C_kn`` are multinomial coefficients such that ``n=k1+k2+..+km``. - For example: + Examples + ======== >>> from sympy import multinomial_coefficients >>> multinomial_coefficients(2, 5) == {(0, 5): 1, (1, 4): 5, ... (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1} True - The algorithm is based on the following result: + Notes + ===== + + The algorithm is based on the following result. - Consider a polynomial and its ``n``-th exponent:: + Consider a polynomial and its ``n``-th exponent:: - P(x) = sum_{i=0}^m p_i x^i - P(x)^n = sum_{k=0}^{m n} a(n,k) x^k + P(x) = sum_{i=0}^m p_i x^i + P(x)^n = sum_{k=0}^{m n} a(n,k) x^k - The coefficients ``a(n,k)`` can be computed using the - J.C.P. Miller Pure Recurrence [see D.E.Knuth, Seminumerical - Algorithms, The art of Computer Programming v.2, Addison - Wesley, Reading, 1981;]:: + The coefficients ``a(n,k)`` can be computed using the + J.C.P. Miller Pure Recurrence [see D.E.Knuth, Seminumerical + Algorithms, The art of Computer Programming v.2, Addison + Wesley, Reading, 1981;]:: - a(n,k) = 1/(k p_0) sum_{i=1}^m p_i ((n+1)i-k) a(n,k-i), + a(n,k) = 1/(k p_0) sum_{i=1}^m p_i ((n+1)i-k) a(n,k-i), - where ``a(n,0) = p_0^n``. + where ``a(n,0) = p_0^n``. """ if not m: @@ -114,24 +118,24 @@ def multinomial_coefficients0(m, n, _tuple=tuple, _zip=zip): def multinomial_coefficients(m, n): r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}`` - where ``C_kn`` are multinomial coefficients such that - ``n=k1+k2+..+km``. + where ``C_kn`` are multinomial coefficients such that ``n=k1+k2+..+km``. - For example: + Examples + ======== >>> from sympy.ntheory import multinomial_coefficients >>> multinomial_coefficients(2, 5) == {(0, 5): 1, (1, 4): 5, ... (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1} True + Notes + ===== + The algorithm is based on the following result: .. math:: - \binom{n}{k_1, \ldots, k_m} = - \frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots} - - Code contributed to Sage by Yann Laigle-Chapuy, copied with permission - of the author. + \binom{n}{k_1, \ldots, k_m} = \frac{k_1 + 1}{n - k_1} + \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots} See Also ======== diff --git a/sympy/ntheory/residue_ntheory.py b/sympy/ntheory/residue_ntheory.py index 0154bca9043..1046f18f12d 100644 --- a/sympy/ntheory/residue_ntheory.py +++ b/sympy/ntheory/residue_ntheory.py @@ -53,13 +53,12 @@ def n_order(a, n): return order def _primitive_root_prime_iter(p): - """ - Generates the primitive roots for a prime ``p`` + """Generates the primitive roots for a prime ``p`` References ========== - [1] W. Stein "Elementary Number Theory" (2011), page 44 + .. [1] W. Stein "Elementary Number Theory" (2011), page 44 Examples ======== @@ -80,14 +79,13 @@ def _primitive_root_prime_iter(p): a += 1 def primitive_root(p): - """ - Returns the smallest primitive root or None + """Returns the smallest primitive root or None. References ========== - [1] W. Stein "Elementary Number Theory" (2011), page 44 - [2] P. Hackman "Elementary Number Theory" (2009), Chapter C + .. [1] W. Stein "Elementary Number Theory" (2011), page 44 + .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C Parameters ========== @@ -144,11 +142,10 @@ def primitive_root(p): return next(_primitive_root_prime_iter(p)) def is_primitive_root(a, p): - """ - Returns True if ``a`` is a primitive root of ``p`` + """Returns True if ``a`` is a primitive root of ``p`` ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and - totient(p) is the smallest positive number s.t. + totient(p) is the smallest positive number s.t.:: a**totient(p) cong 1 mod(p) @@ -164,7 +161,6 @@ def is_primitive_root(a, p): True >>> n_order(9, 10) == totient(10) False - """ a, p = as_int(a), as_int(p) if igcd(a, p) != 1: @@ -174,13 +170,12 @@ def is_primitive_root(a, p): return n_order(a, p) == totient(p) def _sqrt_mod_tonelli_shanks(a, p): - """ - Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)`` + """Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)`` References ========== - R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101 + .. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101 """ s = trailing(p - 1) t = p >> s @@ -204,8 +199,7 @@ def _sqrt_mod_tonelli_shanks(a, p): return x def sqrt_mod(a, p, all_roots=False): - """ - find a root of ``x**2 = a mod p`` + """Find a root of ``x**2 = a mod p``. Parameters ========== @@ -255,17 +249,13 @@ def sqrt_mod(a, p, all_roots=False): return None def _product(*iters): - """ - cartesian product generator + """Cartesian product generator. Notes ===== Unlike itertools.product, it works also with iterables which do not fit - in memory. See http://bugs.python.org/issue10109 - - Author: Fernando Sumudu - with small changes + in memory. See http://bugs.python.org/issue10109. """ import itertools inf_iters = tuple(itertools.cycle(enumerate(it)) for it in iters) @@ -289,8 +279,7 @@ def _product(*iters): def sqrt_mod_iter(a, p, domain=int): - """ - iterate over solutions to ``x**2 = a mod p`` + """Iterate over solutions to ``x**2 = a mod p``. Parameters ========== @@ -349,8 +338,7 @@ def sqrt_mod_iter(a, p, domain=int): def _sqrt_mod_prime_power(a, p, k): - """ - find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0`` + """Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``. Parameters ========== @@ -362,9 +350,9 @@ def _sqrt_mod_prime_power(a, p, k): References ========== - [1] P. Hackman "Elementary Number Theory" (2009), page 160 - [2] http://www.numbertheory.org/php/squareroot.html - [3] [Gathen99]_ + .. [1] P. Hackman "Elementary Number Theory" (2009), page 160 + .. [2] http://www.numbertheory.org/php/squareroot.html + .. [3] [Gathen99]_ Examples ======== @@ -466,10 +454,12 @@ def _sqrt_mod_prime_power(a, p, k): return [r, px - r] def _sqrt_mod1(a, p, n): - """ - find solution to ``x**2 == a mod p**n`` when ``a % p == 0`` + """Find solution to ``x**2 == a mod p**n`` when ``a % p == 0`` + + References + ========== - see http://www.numbertheory.org/php/squareroot.html + .. [1] http://www.numbertheory.org/php/squareroot.html """ pn = p**n a = a % pn @@ -607,13 +597,12 @@ def is_quad_residue(a, p): def is_nthpow_residue(a, n, m): - """ - Returns True if ``x**n == a (mod m)`` has solutions. + """Returns True if ``x**n == a (mod m)`` has solutions. References ========== - P. Hackman "Elementary Number Theory" (2009), page 76 + .. [1] P. Hackman "Elementary Number Theory" (2009), page 76 """ if n == 1: return True @@ -633,13 +622,12 @@ def _nthroot_mod2(s, q, p): return s def _nthroot_mod1(s, q, p, all_roots): - """ - Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1`` + """Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``. References ========== - [1] A. M. Johnston "A Generalized qth Root Algorithm" + .. [1] A. M. Johnston "A Generalized qth Root Algorithm" """ g = primitive_root(p) if not isprime(q): @@ -687,8 +675,7 @@ def _nthroot_mod1(s, q, p, all_roots): return min(res) def nthroot_mod(a, n, p, all_roots=False): - """ - find the solutions to ``x**n = a mod p`` + """Find the solutions to ``x**n = a mod p``. Parameters ========== @@ -750,8 +737,7 @@ def nthroot_mod(a, n, p, all_roots=False): return res def quadratic_residues(p): - """ - Returns the list of quadratic residues. + """Returns the list of quadratic residues. Examples ======== @@ -767,7 +753,8 @@ def quadratic_residues(p): def legendre_symbol(a, p): - """ + """Legendre symbol function [1]_. + Returns ======= @@ -791,6 +778,10 @@ def legendre_symbol(a, p): is_quad_residue, jacobi_symbol + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Legendre_symbol """ a, p = as_int(a), as_int(p) if not isprime(p) or p == 2: @@ -804,8 +795,7 @@ def legendre_symbol(a, p): def jacobi_symbol(m, n): - """ - Returns the product of the legendre_symbol(m, p) + """Returns the product of the legendre_symbol(m, p) for all the prime factors, p, of n. Returns @@ -869,8 +859,7 @@ def jacobi_symbol(m, n): class mobius(Function): - """ - Möbius function maps natural number to {-1, 0, 1} + """Möbius function maps natural number to {-1, 0, 1} It is defined as follows: 1) `1` if `n = 1`. @@ -906,7 +895,6 @@ class mobius(Function): .. [1] http://en.wikipedia.org/wiki/M%C3%B6bius_function .. [2] Thomas Koshy "Elementary Number Theory with Applications" - """ @classmethod def eval(cls, n): diff --git a/sympy/ntheory/tests/test_ntheory.py b/sympy/ntheory/tests/test_ntheory.py index 14577e219ba..11b7d810501 100644 --- a/sympy/ntheory/tests/test_ntheory.py +++ b/sympy/ntheory/tests/test_ntheory.py @@ -18,7 +18,6 @@ antidivisors, antidivisor_count, core from sympy.ntheory.generate import cycle_length from sympy.ntheory.primetest import _mr_safe_helper, mr -from sympy.ntheory.bbp_pi import pi_hex_digits from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence from sympy.ntheory.continued_fraction import \ (continued_fraction_periodic as cf_p, @@ -202,7 +201,8 @@ def test_generate(): assert mr(1, [2]) is False - func = lambda i: (i**2 + 1) % 51 + def func(i): + return (i**2 + 1) % 51 assert next(cycle_length(func, 4)) == (6, 2) assert list(cycle_length(func, 4, values=True)) == \ [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14] @@ -479,7 +479,6 @@ def test_residue(): raises(ValueError, lambda: is_quad_residue(1.1, 2)) raises(ValueError, lambda: is_quad_residue(2, 0)) - assert quadratic_residues(12) == [0, 1, 4, 9] assert quadratic_residues(13) == [0, 1, 3, 4, 9, 10, 12] assert [len(quadratic_residues(i)) for i in range(1, 20)] == \ @@ -536,8 +535,8 @@ def test_residue(): assert pow(next(it), 2, p) == a assert type(next(sqrt_mod_iter(9, 27))) is int - assert type(next(sqrt_mod_iter(9, 27, ZZ))) is type(ZZ(1)) - assert type(next(sqrt_mod_iter(1, 7, ZZ))) is type(ZZ(1)) + assert isinstance(next(sqrt_mod_iter(9, 27, ZZ)), type(ZZ(1))) + assert isinstance(next(sqrt_mod_iter(1, 7, ZZ)), type(ZZ(1))) assert is_nthpow_residue(2, 1, 5) assert not is_nthpow_residue(2, 2, 5) @@ -596,12 +595,6 @@ def test_residue(): raises(ValueError, lambda: mobius(i)) -def test_hex_pi_nth_digits(): - assert pi_hex_digits(0) == '3243f6a8885a30' - assert pi_hex_digits(1) == '243f6a8885a308' - assert pi_hex_digits(10000) == '68ac8fcfb8016c' - - def test_crt(): def mcrt(m, v, r, symmetric=False): assert crt(m, v, symmetric)[0] == r diff --git a/sympy/parsing/tests/test_implicit_multiplication_application.py b/sympy/parsing/tests/test_implicit_multiplication_application.py index 01c30e64fe3..31943d930a8 100644 --- a/sympy/parsing/tests/test_implicit_multiplication_application.py +++ b/sympy/parsing/tests/test_implicit_multiplication_application.py @@ -71,7 +71,6 @@ def test_implicit_application(): lambda: parse_expr('sin**2(x)', transformations=transformations2)) - def test_function_exponentiation(): cases = { 'sin**2(x)': 'sin(x)**2', diff --git a/sympy/plotting/intervalmath/lib_interval.py b/sympy/plotting/intervalmath/lib_interval.py index 35bf7ae4a70..06494fd9798 100644 --- a/sympy/plotting/intervalmath/lib_interval.py +++ b/sympy/plotting/intervalmath/lib_interval.py @@ -6,7 +6,6 @@ """ The module contains implemented functions for interval arithmetic.""" - def Abs(x): if isinstance(x, (int, float)): return interval(abs(x)) diff --git a/sympy/polys/agca/homomorphisms.py b/sympy/polys/agca/homomorphisms.py index 1b403e75946..97add90923d 100644 --- a/sympy/polys/agca/homomorphisms.py +++ b/sympy/polys/agca/homomorphisms.py @@ -459,9 +459,11 @@ def __init__(self, domain, codomain, matrix): def _sympy_matrix(self): """Helper function which returns a sympy matrix ``self.matrix``.""" from sympy.matrices import Matrix - c = lambda x: x + def c(x): + return x if isinstance(self.codomain, (QuotientModule, SubQuotientModule)): - c = lambda x: x.data + def c(x): + return x.data return Matrix([[self.ring.to_sympy(y) for y in c(x)] for x in self.matrix]).T def __repr__(self): diff --git a/sympy/polys/agca/modules.py b/sympy/polys/agca/modules.py index 9479aa46d8c..371b227f34f 100644 --- a/sympy/polys/agca/modules.py +++ b/sympy/polys/agca/modules.py @@ -1005,8 +1005,10 @@ def quotient_hom(self): return self.base.identity_hom().quotient_codomain(self.killed_module) -_subs0 = lambda x: x[0] -_subs1 = lambda x: x[1:] +def _subs0(x): + return x[0] +def _subs1(x): + return x[1:] class ModuleOrder(ProductOrder): diff --git a/sympy/polys/compatibility.py b/sympy/polys/compatibility.py index e2b9e04e53a..49e13ebde17 100644 --- a/sympy/polys/compatibility.py +++ b/sympy/polys/compatibility.py @@ -604,10 +604,10 @@ def dmp_qq_collins_resultant(self, f, g): res = dmp_qq_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) return self[1:].from_dense(res) - def dup_resultant(self, f, g): #, includePRS=False): - return dup_resultant(self.to_dense(f), self.to_dense(g), self.domain) #, includePRS=includePRS) - def dmp_resultant(self, f, g): #, includePRS=False): - res = dmp_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) #, includePRS=includePRS) + def dup_resultant(self, f, g): + return dup_resultant(self.to_dense(f), self.to_dense(g), self.domain) + def dmp_resultant(self, f, g): + res = dmp_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) if isinstance(res, list): return self[1:].from_dense(res) else: diff --git a/sympy/polys/constructor.py b/sympy/polys/constructor.py index bffab301996..e69de1b0ca8 100644 --- a/sympy/polys/constructor.py +++ b/sympy/polys/constructor.py @@ -16,9 +16,11 @@ def _construct_simple(coeffs, opt): result, rationals, reals, algebraics = {}, False, False, False if opt.extension is True: - is_algebraic = lambda coeff: coeff.is_number and coeff.is_algebraic + def is_algebraic(coeff): + return coeff.is_number and coeff.is_algebraic else: - is_algebraic = lambda coeff: False + def is_algebraic(coeff): + return False # XXX: add support for a + b*I coefficients for coeff in coeffs: @@ -123,7 +125,7 @@ def _construct_composite(coeffs, opt): if opt.composite is None: if any(gen.is_number for gen in gens): - return None # generators are number-like so lets better use EX + return None # generators are number-like so lets better use EX all_symbols = set() @@ -131,7 +133,7 @@ def _construct_composite(coeffs, opt): symbols = gen.free_symbols if all_symbols & symbols: - return None # there could be algebraic relations between generators + return None # there could be algebraic relations between generators else: all_symbols |= symbols diff --git a/sympy/polys/distributedmodules.py b/sympy/polys/distributedmodules.py index b658ae5b199..689b30ad3ba 100644 --- a/sympy/polys/distributedmodules.py +++ b/sympy/polys/distributedmodules.py @@ -647,7 +647,8 @@ def Ssugar(i, j): Sugars[j] - sdm_monomial_deg(LMj)) \ + sdm_monomial_deg(sdm_monomial_lcm(LMi, LMj)) - ourkey = lambda p: (p[2], O(p[3]), p[1]) + def ourkey(p): + return (p[2], O(p[3]), p[1]) def update(f, sugar, P): """Add f with sugar ``sugar`` to S, update P.""" @@ -682,7 +683,7 @@ def removethis(pair): remove.add(j) # TODO mergesort? - P.extend(reversed([p for i, p in enumerate(N) if not i in remove])) + P.extend(reversed([p for i, p in enumerate(N) if i not in remove])) P.sort(key=ourkey, reverse=True) # NOTE reverse-sort, because we want to pop from the end return P diff --git a/sympy/polys/domains/domain.py b/sympy/polys/domains/domain.py index f8f4ba67340..c9a173514c5 100644 --- a/sympy/polys/domains/domain.py +++ b/sympy/polys/domains/domain.py @@ -133,7 +133,7 @@ def convert(self, element, base=None): return self.from_sympy(element) except (TypeError, ValueError): pass - else: # TODO: remove this branch + else: # TODO: remove this branch if not is_sequence(element): try: element = sympify(element) @@ -147,7 +147,7 @@ def convert(self, element, base=None): def of_type(self, element): """Check if ``a`` is of type ``dtype``. """ - return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement + return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement def __contains__(self, a): """Check if ``a`` belongs to this domain. """ diff --git a/sympy/polys/fields.py b/sympy/polys/fields.py index 4566bad5eca..c5240335c53 100644 --- a/sympy/polys/fields.py +++ b/sympy/polys/fields.py @@ -103,7 +103,8 @@ def __ne__(self, other): def raw_new(self, numer, denom=None): return self.dtype(numer, denom) def new(self, numer, denom=None): - if denom is None: denom = self.ring.one + if denom is None: + denom = self.ring.one numer, denom = numer.cancel(denom) return self.raw_new(numer, denom) diff --git a/sympy/polys/groebnertools.py b/sympy/polys/groebnertools.py index d5cc3b0f656..a821786e331 100644 --- a/sympy/polys/groebnertools.py +++ b/sympy/polys/groebnertools.py @@ -108,7 +108,7 @@ def normal(g, J): else: h = h.monic() - if not h in I: + if h not in I: I[h] = len(f) f.append(h) diff --git a/sympy/polys/heuristicgcd.py b/sympy/polys/heuristicgcd.py index b9ccfc9846e..ed899f4a9b5 100644 --- a/sympy/polys/heuristicgcd.py +++ b/sympy/polys/heuristicgcd.py @@ -127,7 +127,8 @@ def _gcd_interpolate(h, x, ring): if ring.ngens == 1: while h: g = h % x - if g > x // 2: g -= x + if g > x // 2: + g -= x h = (h - g) // x # f += X**i*g @@ -148,4 +149,4 @@ def _gcd_interpolate(h, x, ring): if f.LC < 0: return -f else: - return f + return f diff --git a/sympy/polys/modulargcd.py b/sympy/polys/modulargcd.py index d916146ac6b..286357955e9 100644 --- a/sympy/polys/modulargcd.py +++ b/sympy/polys/modulargcd.py @@ -516,7 +516,7 @@ def _degree_bound_bivariate(f, g): gp = g.trunc_ground(p) contfp, fp = _primitive(fp, p) contgp, gp = _primitive(gp, p) - conthp = _gf_gcd(contfp, contgp, p) # polynomial in Z_p[y] + conthp = _gf_gcd(contfp, contgp, p) # polynomial in Z_p[y] ycontbound = conthp.degree() # polynomial in Z_p[y] @@ -812,7 +812,7 @@ def modgcd_bivariate(f, g): gp = g.trunc_ground(p) contfp, fp = _primitive(fp, p) contgp, gp = _primitive(gp, p) - conthp = _gf_gcd(contfp, contgp, p) # monic polynomial in Z_p[y] + conthp = _gf_gcd(contfp, contgp, p) # monic polynomial in Z_p[y] degconthp = conthp.degree() if degconthp > ycontbound: @@ -847,7 +847,7 @@ def modgcd_bivariate(f, g): fpa = fp.evaluate(1, a).trunc_ground(p) gpa = gp.evaluate(1, a).trunc_ground(p) - hpa = _gf_gcd(fpa, gpa, p) # monic polynomial in Z_p[x] + hpa = _gf_gcd(fpa, gpa, p) # monic polynomial in Z_p[x] deghpa = hpa.degree() if deghpa > xbound: @@ -978,7 +978,7 @@ def _modgcd_multivariate_p(f, g, p, degbound, contbound): contf, f = _primitive(f, p) contg, g = _primitive(g, p) - conth = _gf_gcd(contf, contg, p) # polynomial in Z_p[y] + conth = _gf_gcd(contf, contg, p) # polynomial in Z_p[y] degcontf = contf.degree() degcontg = contg.degree() @@ -993,7 +993,7 @@ def _modgcd_multivariate_p(f, g, p, degbound, contbound): lcf = _LC(f) lcg = _LC(g) - delta = _gf_gcd(lcf, lcg, p) # polynomial in Z_p[y] + delta = _gf_gcd(lcf, lcg, p) # polynomial in Z_p[y] evaltest = delta @@ -1435,14 +1435,14 @@ def _euclidean_algorithm(f, g, minpoly, p): while g: rem = f - deg = g.degree(0) # degree in x + deg = g.degree(0) # degree in x lcinv, _, gcd = _gf_gcdex(ring.dmp_LC(g), minpoly, p) if not gcd == 1: return None while True: - degrem = rem.degree(0) # degree in x + degrem = rem.degree(0) # degree in x if degrem < deg: break quo = (lcinv * ring.dmp_LC(rem)).set_ring(ring) @@ -1583,7 +1583,7 @@ def _func_field_modgcd_p(f, g, minpoly, p): """ ring = f.ring - domain = ring.domain # Z[t_1, ..., t_k] + domain = ring.domain # Z[t_1, ..., t_k] if isinstance(domain, PolynomialRing): k = domain.ngens @@ -1596,7 +1596,7 @@ def _func_field_modgcd_p(f, g, minpoly, p): qdomain = domain.ring.drop_to_ground(k - 1) qdomain = qdomain.clone(domain=qdomain.domain.ring.to_field()) - qring = ring.clone(domain=qdomain) # = Z(t_k)[t_1, ..., t_{k-1}][x, z] + qring = ring.clone(domain=qdomain) # = Z(t_k)[t_1, ..., t_{k-1}][x, z] n = 1 d = 1 @@ -1748,7 +1748,7 @@ def _integer_rational_reconstruction(c, m, domain): r0, s0 = m, domain.zero r1, s1 = c, domain.one - bound = sqrt(m / 2) # still correct if replaced by ZZ.sqrt(m // 2) ? + bound = sqrt(m / 2) # still correct if replaced by ZZ.sqrt(m // 2) ? while r1 >= bound: quo = r0 // r1 @@ -1983,7 +1983,7 @@ def _func_field_modgcd_m(f, g, minpoly): h = h.primitive()[1] if not (_trial_division(f.mul_ground(cf), h, minpoly) or - _trial_division(g.mul_ground(cg), h, minpoly)): + _trial_division(g.mul_ground(cg), h, minpoly)): return h diff --git a/sympy/polys/polyclasses.py b/sympy/polys/polyclasses.py index 10bc0d30147..2c9cb9bf114 100644 --- a/sympy/polys/polyclasses.py +++ b/sympy/polys/polyclasses.py @@ -1528,7 +1528,8 @@ def unify(f, g): else: mod = g.mod - per = lambda rep: ANP(rep, mod, dom) + def per(rep): + return ANP(rep, mod, dom) return dom, per, F, G, mod diff --git a/sympy/polys/polyoptions.py b/sympy/polys/polyoptions.py index f904f2e737b..acb37755011 100644 --- a/sympy/polys/polyoptions.py +++ b/sympy/polys/polyoptions.py @@ -747,7 +747,7 @@ def allowed_flags(args, flags): for arg in args.keys(): try: - if Options.__options__[arg].is_Flag and not arg in flags: + if Options.__options__[arg].is_Flag and arg not in flags: raise FlagError( "'%s' flag is not allowed in this context" % arg) except KeyError: diff --git a/sympy/polys/rings.py b/sympy/polys/rings.py index 09f00ba54e8..bb41bdf0399 100644 --- a/sympy/polys/rings.py +++ b/sympy/polys/rings.py @@ -730,7 +730,7 @@ def drop_to_ground(self, gen): for monom, coeff in self.iterterms(): mon = monom[:i] + monom[i+1:] - if not mon in poly: + if mon not in poly: poly[mon] = (gen**monom[i]).mul_ground(coeff) else: poly[mon] += (gen**monom[i]).mul_ground(coeff) @@ -1134,7 +1134,7 @@ def __pow__(self, n): return self.square() elif n == 3: return self*self.square() - elif len(self) <= 5: # TODO: use an actuall density measure + elif len(self) <= 5: # TODO: use an actuall density measure return self._pow_multinomial(n) else: return self._pow_generic(n) @@ -1313,7 +1313,7 @@ def _term_div(self): def term_div(a_lm_a_lc, b_lm_b_lc): a_lm, a_lc = a_lm_a_lc b_lm, b_lc = b_lm_b_lc - if b_lm == zm: # apparently this is a very common case + if b_lm == zm: # apparently this is a very common case monom = a_lm else: monom = monomial_div(a_lm, b_lm) @@ -1325,7 +1325,7 @@ def term_div(a_lm_a_lc, b_lm_b_lc): def term_div(a_lm_a_lc, b_lm_b_lc): a_lm, a_lc = a_lm_a_lc b_lm, b_lc = b_lm_b_lc - if b_lm == zm: # apparently this is a very common case + if b_lm == zm: # apparently this is a very common case monom = a_lm else: monom = monomial_div(a_lm, b_lm) @@ -2110,7 +2110,7 @@ def _gcd(f, g): return f._gcd_QQ(g) elif ring.domain.is_ZZ: return f._gcd_ZZ(g) - else: # TODO: don't use dense representation (port PRS algorithms) + else: # TODO: don't use dense representation (port PRS algorithms) return ring.dmp_inner_gcd(f, g) def _gcd_ZZ(f, g): diff --git a/sympy/polys/rootoftools.py b/sympy/polys/rootoftools.py index ee67481d930..08de6b085d8 100644 --- a/sympy/polys/rootoftools.py +++ b/sympy/polys/rootoftools.py @@ -233,7 +233,7 @@ def is_imag(c): return True # both imag elif _ispow2(deg): if f.LC()*f.TC() < 0: - return None # 2 are imag + return None # 2 are imag return False # none are imag # separate according to the function sifted = sift(complexes, lambda c: c[1]) @@ -907,7 +907,7 @@ def bisect(f, a, b, tol): c = (a + b)/2 fc = f(c) if (fc == 0): - return c # We need to make sure f(c) is not zero below + return c # We need to make sure f(c) is not zero below if (fa * fc < 0): b = c fb = fc diff --git a/sympy/polys/tests/test_densebasic.py b/sympy/polys/tests/test_densebasic.py index 2e9fcadc131..18526ae101e 100644 --- a/sympy/polys/tests/test_densebasic.py +++ b/sympy/polys/tests/test_densebasic.py @@ -665,7 +665,8 @@ def test_dmp_list_terms(): def test_dmp_apply_pairs(): - h = lambda a, b: a*b + def h(a, b): + return a*b assert dmp_apply_pairs([1, 2, 3], [4, 5, 6], h, [], 0, ZZ) == [4, 10, 18] diff --git a/sympy/polys/tests/test_polytools.py b/sympy/polys/tests/test_polytools.py index b0122de5914..cb767777683 100644 --- a/sympy/polys/tests/test_polytools.py +++ b/sympy/polys/tests/test_polytools.py @@ -1300,7 +1300,8 @@ def test_Poly_LM(): def test_Poly_LM_custom_order(): f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1) - rev_lex = lambda monom: tuple(reversed(monom)) + def rev_lex(monom): + return tuple(reversed(monom)) assert f.LM(order='lex') == (2, 3, 1) assert f.LM(order=rev_lex) == (2, 1, 3) @@ -2763,7 +2764,6 @@ def test_torational_factor_list(): (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) - p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))})) assert _torational_factor_list(p, x) is None diff --git a/sympy/polys/tests/test_rootoftools.py b/sympy/polys/tests/test_rootoftools.py index 8497731ba85..82f994d8da1 100644 --- a/sympy/polys/tests/test_rootoftools.py +++ b/sympy/polys/tests/test_rootoftools.py @@ -114,7 +114,6 @@ def test_RootOf_attributes(): raises(NotImplementedError, lambda: RootOf(Poly(x**3 + y*x + 1, x), 0)) - def test_RootOf___eq__(): assert (RootOf(x**3 + x + 3, 0) == RootOf(x**3 + x + 3, 0)) is True assert (RootOf(x**3 + x + 3, 0) == RootOf(x**3 + x + 3, 1)) is False diff --git a/sympy/printing/dot.py b/sympy/printing/dot.py index e6b8c819a8c..5d4b6be507e 100644 --- a/sympy/printing/dot.py +++ b/sympy/printing/dot.py @@ -121,8 +121,9 @@ def dotedges(expr, atom=lambda x: not isinstance(x, Basic), pos=(), repeat=True) graphstyle = {'rankdir': 'TD', 'ordering': 'out'} -def dotprint(expr, styles=default_styles, atom=lambda x: not isinstance(x, - Basic), maxdepth=None, repeat=True, labelfunc=str, **kwargs): +def dotprint(expr, styles=default_styles, + atom=lambda x: not isinstance(x, Basic), + maxdepth=None, repeat=True, labelfunc=str, **kwargs): """ DOT description of a SymPy expression tree diff --git a/sympy/printing/fcode.py b/sympy/printing/fcode.py index 061828fceb7..50adf9e7a2d 100644 --- a/sympy/printing/fcode.py +++ b/sympy/printing/fcode.py @@ -296,11 +296,11 @@ def split_pos_code(line, endpos): if len(line) <= endpos: return len(line) pos = endpos - split = lambda pos: \ - (line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \ - (line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \ - (line[pos] in my_white and line[pos - 1] not in my_white) or \ - (line[pos] not in my_white and line[pos - 1] in my_white) + def split(pos): + return (line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \ + (line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \ + (line[pos] in my_white and line[pos - 1] not in my_white) or \ + (line[pos] not in my_white and line[pos - 1] in my_white) while not split(pos): pos -= 1 if pos == 0: diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py index 97d4a25e92e..67b35f4b70c 100644 --- a/sympy/printing/latex.py +++ b/sympy/printing/latex.py @@ -220,7 +220,6 @@ def _needs_mul_brackets(self, expr, first=False, last=False): return False - def _needs_add_brackets(self, expr): """ Returns True if the expression needs to be wrapped in brackets when @@ -231,7 +230,6 @@ def _needs_add_brackets(self, expr): return True return False - def _mul_is_clean(self, expr): for arg in expr.args: if arg.is_Function: @@ -256,7 +254,6 @@ def _print_bool(self, e): def _print_NoneType(self, e): return r"\mathrm{%s}" % e - def _print_Add(self, expr, order=None): if self.order == 'none': terms = list(expr.args) @@ -279,7 +276,6 @@ def _print_Add(self, expr, order=None): return tex - def _print_Float(self, expr): # Based off of that in StrPrinter dps = prec_to_dps(expr._prec) @@ -354,7 +350,7 @@ def convert(expr): ldenom = len(sdenom.split()) ratio = self._settings['long_frac_ratio'] if self._settings['fold_short_frac'] \ - and ldenom <= 2 and not "^" in sdenom: + and ldenom <= 2 and "^" not in sdenom: # handle short fractions if self._needs_mul_brackets(numer, last=False): tex += r"\left(%s\right) / %s" % (snumer, sdenom) @@ -523,7 +519,6 @@ def _print_Derivative(self, expr): else: diff_symbol = r'd' - if dim == 1: tex = r"\frac{%s}{%s %s}" % (diff_symbol, diff_symbol, self._print(expr.variables[0])) diff --git a/sympy/printing/mathml.py b/sympy/printing/mathml.py index 6ae1a937d0d..ca7d91e4b81 100644 --- a/sympy/printing/mathml.py +++ b/sympy/printing/mathml.py @@ -269,7 +269,7 @@ def join(items): return mi # translate name, supers and subs to unicode characters - greek_letters = set(greeks) # make a copy + greek_letters = set(greeks) # make a copy def translate(s): if s in greek_unicode: return greek_unicode.get(s) @@ -451,10 +451,9 @@ def print_mathml(expr, **settings): Examples ======== - >>> ## >>> from sympy.printing.mathml import print_mathml >>> from sympy.abc import x - >>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE + >>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE x diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py index eb0aca48c0d..c6d89906736 100644 --- a/sympy/printing/octave.py +++ b/sympy/printing/octave.py @@ -67,33 +67,26 @@ def __init__(self, settings={}): userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) - def _rate_index_position(self, p): return p*5 - def _get_statement(self, codestring): return "%s;" % codestring - def _get_comment(self, text): return "% {0}".format(text) - def _declare_number_const(self, name, value): return "{0} = {1};".format(name, value) - def _format_code(self, lines): return self.indent_code(lines) - def _traverse_matrix_indices(self, mat): # Octave uses Fortran order (column-major) rows, cols = mat.shape return ((i, j) for j in range(cols) for i in range(rows)) - def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] @@ -105,7 +98,6 @@ def _get_loop_opening_ending(self, indices): close_lines.append("end") return open_lines, close_lines - def _print_Mul(self, expr): # print complex numbers nicely in Octave if (expr.is_number and expr.is_imaginary and @@ -171,7 +163,6 @@ def multjoin(a, a_str): return (sign + multjoin(a, a_str) + divsym + "(%s)" % multjoin(b, b_str)) - def _print_Pow(self, expr): powsymbol = '^' if all([x.is_number for x in expr.args]) else '.^' @@ -191,31 +182,25 @@ def _print_Pow(self, expr): return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol, self.parenthesize(expr.exp, PREC)) - def _print_MatPow(self, expr): PREC = precedence(expr) return '%s^%s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) - def _print_Pi(self, expr): return 'pi' - def _print_ImaginaryUnit(self, expr): return "1i" - def _print_Exp1(self, expr): return "exp(1)" - def _print_GoldenRatio(self, expr): # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)? #return self._print((1+sqrt(S(5)))/2) return "(1+sqrt(5))/2" - def _print_NumberSymbol(self, expr): if self._settings["inline"]: return self._print(expr.evalf(self._settings["precision"])) @@ -223,7 +208,6 @@ def _print_NumberSymbol(self, expr): # assign to a variable, perhaps more readable for longer program return super(OctaveCodePrinter, self)._print_NumberSymbol(expr) - def _print_Assignment(self, expr): from sympy.functions.elementary.piecewise import Piecewise from sympy.tensor.indexed import IndexedBase @@ -251,41 +235,32 @@ def _print_Assignment(self, expr): rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) - def _print_Infinity(self, expr): return 'inf' - def _print_NegativeInfinity(self, expr): return '-inf' - def _print_NaN(self, expr): return 'NaN' - def _print_list(self, expr): return '{' + ', '.join(self._print(a) for a in expr) + '}' _print_tuple = _print_list _print_Tuple = _print_list - def _print_BooleanTrue(self, expr): return "true" - def _print_BooleanFalse(self, expr): return "false" - def _print_bool(self, expr): return str(expr).lower() - # Could generate quadrature code for definite Integrals? #_print_Integral = _print_not_supported - def _print_MatrixBase(self, A): # Handle zero dimensions: if (A.rows, A.cols) == (0, 0): @@ -303,10 +278,9 @@ def _print_MatrixBase(self, A): return "[%s]" % A.table(self, rowstart='', rowend='', rowsep=';\n', colsep=' ') - def _print_SparseMatrix(self, A): from sympy.matrices import Matrix - L = A.col_list(); + L = A.col_list() # make row vectors of the indices and entries I = Matrix([[k[0] + 1 for k in L]]) J = Matrix([[k[1] + 1 for k in L]]) @@ -314,7 +288,6 @@ def _print_SparseMatrix(self, A): return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), self._print(AIJ), A.rows, A.cols) - # FIXME: Str/CodePrinter could define each of these to call the _print # method from higher up the class hierarchy (see _print_NumberSymbol). # Then subclasses like us would not need to repeat all this. @@ -328,11 +301,9 @@ def _print_SparseMatrix(self, A): _print_ImmutableSparseMatrix = \ _print_SparseMatrix - def _print_MatrixElement(self, expr): return self._print(expr.parent) + '(%s, %s)'%(expr.i+1, expr.j+1) - def _print_MatrixSlice(self, expr): def strslice(x, lim): l = x[0] + 1 @@ -353,20 +324,16 @@ def strslice(x, lim): strslice(expr.rowslice, expr.parent.shape[0]) + ', ' + strslice(expr.colslice, expr.parent.shape[1]) + ')') - def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds)) - def _print_Idx(self, expr): return self._print(expr.label) - def _print_Identity(self, expr): return "eye(%s)" % self._print(expr.shape[0]) - def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting @@ -403,7 +370,6 @@ def _print_Piecewise(self, expr): lines.append("end") return "\n".join(lines) - def indent_code(self, code): """Accepts a string of code or a list of code lines""" diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py index 2c85f425ec1..53d91d1b7e1 100644 --- a/sympy/printing/pretty/pretty.py +++ b/sympy/printing/pretty/pretty.py @@ -644,7 +644,6 @@ def _print_MatrixBase(self, e): _print_ImmutableMatrix = _print_MatrixBase _print_Matrix = _print_MatrixBase - def _print_MatrixElement(self, expr): from sympy.matrices import MatrixSymbol from sympy import Symbol @@ -665,7 +664,6 @@ def _print_MatrixElement(self, expr): return pform - def _print_MatrixSlice(self, m): # XXX works only for applied functions @@ -1495,7 +1493,6 @@ def _print_Complement(self, u): parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Union) - def _print_ImageSet(self, ts): if self._use_unicode: inn = u("\N{SMALL ELEMENT OF}") diff --git a/sympy/printing/pretty/pretty_symbology.py b/sympy/printing/pretty/pretty_symbology.py index 5f0b71569b3..ff197d5929b 100644 --- a/sympy/printing/pretty/pretty_symbology.py +++ b/sympy/printing/pretty/pretty_symbology.py @@ -26,7 +26,8 @@ def U(name): except ImportError: unicode_warnings += 'No unicodedata available\n' - U = lambda name: None + def U(name): + return from sympy.printing.conventions import split_super_sub from sympy.core.alphabets import greeks @@ -112,10 +113,12 @@ def xstr(*args): return str(*args) # GREEK -g = lambda l: U('GREEK SMALL LETTER %s' % l.upper()) -G = lambda l: U('GREEK CAPITAL LETTER %s' % l.upper()) +def g(l): + return U('GREEK SMALL LETTER %s' % l.upper()) +def G(l): + return U('GREEK CAPITAL LETTER %s' % l.upper()) -greek_letters = list(greeks) # make a copy +greek_letters = list(greeks) # make a copy # deal with Unicode's funny spelling of lambda greek_letters[greek_letters.index('lambda')] = 'lamda' @@ -160,14 +163,21 @@ def xstr(*args): } # SUBSCRIPT & SUPERSCRIPT -LSUB = lambda letter: U('LATIN SUBSCRIPT SMALL LETTER %s' % letter.upper()) -GSUB = lambda letter: U('GREEK SUBSCRIPT SMALL LETTER %s' % letter.upper()) -DSUB = lambda digit: U('SUBSCRIPT %s' % digit_2txt[digit]) -SSUB = lambda symb: U('SUBSCRIPT %s' % symb_2txt[symb]) - -LSUP = lambda letter: U('SUPERSCRIPT LATIN SMALL LETTER %s' % letter.upper()) -DSUP = lambda digit: U('SUPERSCRIPT %s' % digit_2txt[digit]) -SSUP = lambda symb: U('SUPERSCRIPT %s' % symb_2txt[symb]) +def LSUB(letter): + return U('LATIN SUBSCRIPT SMALL LETTER %s' % letter.upper()) +def GSUB(letter): + return U('GREEK SUBSCRIPT SMALL LETTER %s' % letter.upper()) +def DSUB(digit): + return U('SUBSCRIPT %s' % digit_2txt[digit]) +def SSUB(symb): + return U('SUBSCRIPT %s' % symb_2txt[symb]) + +def LSUP(letter): + return U('SUPERSCRIPT LATIN SMALL LETTER %s' % letter.upper()) +def DSUP(digit): + return U('SUPERSCRIPT %s' % digit_2txt[digit]) +def SSUP(symb): + return U('SUPERSCRIPT %s' % symb_2txt[symb]) sub = {} # symb -> subscript symbol sup = {} # symb -> superscript symbol @@ -224,14 +234,22 @@ def xstr(*args): } # VERTICAL OBJECTS -HUP = lambda symb: U('%s UPPER HOOK' % symb_2txt[symb]) -CUP = lambda symb: U('%s UPPER CORNER' % symb_2txt[symb]) -MID = lambda symb: U('%s MIDDLE PIECE' % symb_2txt[symb]) -EXT = lambda symb: U('%s EXTENSION' % symb_2txt[symb]) -HLO = lambda symb: U('%s LOWER HOOK' % symb_2txt[symb]) -CLO = lambda symb: U('%s LOWER CORNER' % symb_2txt[symb]) -TOP = lambda symb: U('%s TOP' % symb_2txt[symb]) -BOT = lambda symb: U('%s BOTTOM' % symb_2txt[symb]) +def HUP(symb): + return U('%s UPPER HOOK' % symb_2txt[symb]) +def CUP(symb): + return U('%s UPPER CORNER' % symb_2txt[symb]) +def MID(symb): + return U('%s MIDDLE PIECE' % symb_2txt[symb]) +def EXT(symb): + return U('%s EXTENSION' % symb_2txt[symb]) +def HLO(symb): + return U('%s LOWER HOOK' % symb_2txt[symb]) +def CLO(symb): + return U('%s LOWER CORNER' % symb_2txt[symb]) +def TOP(symb): + return U('%s TOP' % symb_2txt[symb]) +def BOT(symb): + return U('%s BOTTOM' % symb_2txt[symb]) # {} '(' -> (extension, start, end, middle) 1-character _xobj_unicode = { @@ -401,7 +419,8 @@ def hobj(symb, width): # RATIONAL -VF = lambda txt: U('VULGAR FRACTION %s' % txt) +def VF(txt): + return U('VULGAR FRACTION %s' % txt) # (p,q) -> symbol frac = { diff --git a/sympy/printing/pretty/stringpict.py b/sympy/printing/pretty/stringpict.py index bdd996af460..8ed04572359 100644 --- a/sympy/printing/pretty/stringpict.py +++ b/sympy/printing/pretty/stringpict.py @@ -160,7 +160,7 @@ def below(self, *args): >>> from sympy.printing.pretty.stringpict import stringPict >>> f = pretty_use_unicode(flag=False) >>> print(stringPict("x+3").below( - ... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE + ... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE x+3 --- 3 @@ -434,7 +434,7 @@ def __mul__(self, *others): Parentheses are needed around +, - and neg. """ if len(others) == 0: - return self # We aren't actually multiplying... So nothing to do here. + return self # We aren't actually multiplying... So nothing to do here. args = self if args.binding > prettyForm.MUL: diff --git a/sympy/printing/python.py b/sympy/printing/python.py index dc6d8ffe590..05f8bf13491 100644 --- a/sympy/printing/python.py +++ b/sympy/printing/python.py @@ -30,7 +30,7 @@ def __init__(self, settings=None): def _print_Function(self, expr): func = expr.func.__name__ - if not hasattr(sympy, func) and not func in self.functions: + if not hasattr(sympy, func) and func not in self.functions: self.functions.append(func) return StrPrinter._print_Function(self, expr) diff --git a/sympy/printing/str.py b/sympy/printing/str.py index fe4cbdded72..75f5da11b5f 100644 --- a/sympy/printing/str.py +++ b/sympy/printing/str.py @@ -116,7 +116,6 @@ def _print_dict(self, d): def _print_Dict(self, expr): return self._print_dict(expr) - def _print_RandomDomain(self, d): try: return 'Domain: ' + self._print(d.as_boolean()) @@ -666,7 +665,6 @@ def _print_Union(self, expr): def _print_Complement(self, expr): return ' \ '.join(self._print(set) for set in expr.args) - def _print_Unit(self, expr): return expr.abbrev diff --git a/sympy/printing/tests/test_octave.py b/sympy/printing/tests/test_octave.py index 7faeffc5f7c..01863b653d7 100644 --- a/sympy/printing/tests/test_octave.py +++ b/sympy/printing/tests/test_octave.py @@ -138,7 +138,7 @@ def test_Matrices(): assert mcode(Matrix(1, 1, [10])) == "10" A = Matrix([[1, sin(x/2), abs(x)], [0, 1, pi], - [0, exp(1), ceiling(x)]]); + [0, exp(1), ceiling(x)]]) expected = ("[1 sin(x/2) abs(x);\n" "0 1 pi;\n" "0 exp(1) ceil(x)]") @@ -167,7 +167,7 @@ def test_Matrices_entries_not_hadamard(): # leave it user's responsibility to put scalar data for x. A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]]) expected = ("[1 sin(2/x) 3*pi/(5*x);\n" - "1 2 x*y]") # <- we give x.*y + "1 2 x*y]") # <- we give x.*y assert mcode(A) == expected @@ -310,8 +310,8 @@ def test_octave_not_supported(): def test_trick_indent_with_end_else_words(): # words starting with "end" or "else" do not confuse the indenter - t1 = S('endless'); - t2 = S('elsewhere'); + t1 = S('endless') + t2 = S('elsewhere') pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True)) assert mcode(pw, inline=False) == ( "if (x < 0)\n" @@ -339,11 +339,11 @@ def test_haramard(): def test_sparse(): M = SparseMatrix(5, 6, {}) - M[2, 2] = 10; - M[1, 2] = 20; - M[1, 3] = 22; - M[0, 3] = 30; - M[3, 0] = x*y; + M[2, 2] = 10 + M[1, 2] = 20 + M[1, 3] = 22 + M[0, 3] = 30 + M[3, 0] = x*y assert mcode(M) == ( "sparse([4 2 3 1 2], [1 3 3 4 4], [x.*y 20 10 30 22], 5, 6)" ) diff --git a/sympy/printing/tests/test_theanocode.py b/sympy/printing/tests/test_theanocode.py index b84c403a8cb..15a07c6dfbf 100644 --- a/sympy/printing/tests/test_theanocode.py +++ b/sympy/printing/tests/test_theanocode.py @@ -130,7 +130,8 @@ def test_factorial(): assert theano_code(sympy.factorial(n)) def test_Derivative(): - simp = lambda expr: theano_simplify(fgraph_of(expr)) + def simp(expr): + return theano_simplify(fgraph_of(expr)) assert theq(simp(theano_code(sy.Derivative(sy.sin(x), x, evaluate=False))), simp(theano.grad(tt.sin(xt), xt))) diff --git a/sympy/printing/theanocode.py b/sympy/printing/theanocode.py index 0d8901a8f84..b1b6eb59c90 100644 --- a/sympy/printing/theanocode.py +++ b/sympy/printing/theanocode.py @@ -92,7 +92,6 @@ def _print_AppliedUndef(self, s, dtypes={}, broadcastables={}): self.cache[key] = value return value - def _print_Basic(self, expr, **kwargs): op = mapping[type(expr)] children = [self._print(arg, **kwargs) for arg in expr.args] @@ -142,7 +141,6 @@ def _print_BlockMatrix(self, expr, **kwargs): for r in range(nrows)] return tt.join(0, *[tt.join(1, *row) for row in blocks]) - def _print_slice(self, expr, **kwargs): return slice(*[self._print(i, **kwargs) if isinstance(i, sympy.Basic) else i @@ -211,7 +209,7 @@ def dim_handling(inputs, dim=None, dims={}, broadcastables={}, keys=(), def theano_function(inputs, outputs, dtypes={}, cache=None, **kwargs): """ Create Theano function from SymPy expressions """ - cache = {} if cache == None else cache + cache = {} if cache is None else cache broadcastables = dim_handling(inputs, **kwargs) # Remove keyword arguments corresponding to dim_handling diff --git a/sympy/series/gruntz.py b/sympy/series/gruntz.py index a57135f31d5..d748d546c14 100644 --- a/sympy/series/gruntz.py +++ b/sympy/series/gruntz.py @@ -80,9 +80,9 @@ def compare(a, b, x): Returns ======= - {">", "=", "<"} - ">" if `a(x) \succ b(x)`, "=" if `a(x) \asymp b(x)` - and "<" otherwise. + {1, 0, -1} + Respectively, if `a(x) \succ b(x)`, `a(x) \asymp b(x)` + or `b(x) \succ a(x)`. """ # The log(exp(...)) must always be simplified here for termination. la = a.exp if a.func is exp else log(a) @@ -90,11 +90,11 @@ def compare(a, b, x): c = limitinf(la/lb, x) if c.is_zero: - return "<" + return -1 elif c.is_infinite: - return ">" + return 1 else: - return "=" + return 0 def mrv(e, x): @@ -133,9 +133,9 @@ def mrv_max(f, g, x): return f | g c = compare(list(f)[0], list(g)[0], x) - if c == ">": + if c > 0: return f - elif c == "<": + elif c < 0: return g else: return f | g diff --git a/sympy/series/limits.py b/sympy/series/limits.py index d3b0fa7fc30..0d0b7d16b0d 100644 --- a/sympy/series/limits.py +++ b/sympy/series/limits.py @@ -172,11 +172,11 @@ def doit(self, **hints): # not be handled this way but I'm not sure what that # condition is; when ok is True it means that the leading # term approach is going to succeed (hopefully) - ok = lambda w: (z in w.free_symbols and - any(a.is_polynomial(z) or - any(z in m.free_symbols and m.is_polynomial(z) - for m in Mul.make_args(a)) - for a in Add.make_args(w))) + def ok(w): + return (z in w.free_symbols and any(a.is_polynomial(z) or + any(z in m.free_symbols and m.is_polynomial(z) + for m in Mul.make_args(a)) + for a in Add.make_args(w))) if all(ok(w) for w in e.as_numer_denom()): u = Dummy(positive=True) if z0 is S.Infinity: diff --git a/sympy/series/tests/test_aseries.py b/sympy/series/tests/test_aseries.py index 1337013d496..b1117e8a0db 100644 --- a/sympy/series/tests/test_aseries.py +++ b/sympy/series/tests/test_aseries.py @@ -22,7 +22,8 @@ def test_simple(): e = exp(sin(1/x + exp(-exp(x)))) - exp(sin(1/x)) assert e.aseries(x, n=4) == (-1/(2*x**3) + 1/x + 1 + O(x**(-4), (x, oo)))*exp(-exp(x)) # 6.15 - e3 = lambda x: exp(exp(exp(x))) + def e3(x): + return exp(exp(exp(x))) e = e3(x)/e3(x-1/e3(x)) assert e.aseries(x, n=3) == 1 + exp(x + exp(x))*exp(-exp(exp(x))) + ((-exp(x)/2 - S.Half)*exp(x + exp(x)) + \ exp(2*x + 2*exp(x))/2)*exp(-2*exp(exp(x))) + O(exp(-3*exp(exp(x))), (x, oo)) diff --git a/sympy/series/tests/test_gruntz.py b/sympy/series/tests/test_gruntz.py index 7be16c90dae..c52a4fc8a0b 100644 --- a/sympy/series/tests/test_gruntz.py +++ b/sympy/series/tests/test_gruntz.py @@ -128,48 +128,48 @@ def test_gruntz_hyperbolic(): def test_compare(): - assert compare(Integer(2), x, x) == "<" - assert compare(x, exp(x), x) == "<" - assert compare(exp(x), exp(x**2), x) == "<" - assert compare(exp(x**2), exp(exp(x)), x) == "<" - assert compare(Integer(1), exp(exp(x)), x) == "<" - - assert compare(x, Integer(2), x) == ">" - assert compare(exp(x), x, x) == ">" - assert compare(exp(x**2), exp(x), x) == ">" - assert compare(exp(exp(x)), exp(x**2), x) == ">" - assert compare(exp(exp(x)), Integer(1), x) == ">" - - assert compare(Integer(2), Integer(3), x) == "=" - assert compare(Integer(3), Integer(-5), x) == "=" - assert compare(Integer(2), Integer(-5), x) == "=" - - assert compare(x, x**2, x) == "=" - assert compare(x**2, x**3, x) == "=" - assert compare(x**3, 1/x, x) == "=" - assert compare(1/x, x**m, x) == "=" - assert compare(x**m, -x, x) == "=" - - assert compare(exp(x), exp(-x), x) == "=" - assert compare(exp(-x), exp(2*x), x) == "=" - assert compare(exp(2*x), exp(x)**2, x) == "=" - assert compare(exp(x)**2, exp(x + exp(-x)), x) == "=" - assert compare(exp(x), exp(x + exp(-x)), x) == "=" - - assert compare(exp(x**2), 1/exp(x**2), x) == "=" - - assert compare(exp(x), x**5, x) == ">" - assert compare(exp(x**2), exp(x)**2, x) == ">" - assert compare(exp(x), exp(x + exp(-x)), x) == "=" - assert compare(exp(x + exp(-x)), exp(x), x) == "=" - assert compare(exp(x + exp(-x)), exp(-x), x) == "=" - assert compare(exp(-x), x, x) == ">" - assert compare(x, exp(-x), x) == "<" - assert compare(exp(x + 1/x), x, x) == ">" - assert compare(exp(-exp(x)), exp(x), x) == ">" - assert compare(exp(exp(-exp(x)) + x), exp(-exp(x)), x) == "<" - - assert compare(exp(exp(x)), exp(x + exp(-exp(x))), x) == ">" + assert compare(Integer(2), x, x) < 0 + assert compare(x, exp(x), x) < 0 + assert compare(exp(x), exp(x**2), x) < 0 + assert compare(exp(x**2), exp(exp(x)), x) < 0 + assert compare(Integer(1), exp(exp(x)), x) < 0 + + assert compare(x, Integer(2), x) > 0 + assert compare(exp(x), x, x) > 0 + assert compare(exp(x**2), exp(x), x) > 0 + assert compare(exp(exp(x)), exp(x**2), x) > 0 + assert compare(exp(exp(x)), Integer(1), x) > 0 + + assert compare(Integer(2), Integer(3), x) == 0 + assert compare(Integer(3), Integer(-5), x) == 0 + assert compare(Integer(2), Integer(-5), x) == 0 + + assert compare(x, x**2, x) == 0 + assert compare(x**2, x**3, x) == 0 + assert compare(x**3, 1/x, x) == 0 + assert compare(1/x, x**m, x) == 0 + assert compare(x**m, -x, x) == 0 + + assert compare(exp(x), exp(-x), x) == 0 + assert compare(exp(-x), exp(2*x), x) == 0 + assert compare(exp(2*x), exp(x)**2, x) == 0 + assert compare(exp(x)**2, exp(x + exp(-x)), x) == 0 + assert compare(exp(x), exp(x + exp(-x)), x) == 0 + + assert compare(exp(x**2), 1/exp(x**2), x) == 0 + + assert compare(exp(x), x**5, x) > 0 + assert compare(exp(x**2), exp(x)**2, x) > 0 + assert compare(exp(x), exp(x + exp(-x)), x) == 0 + assert compare(exp(x + exp(-x)), exp(x), x) == 0 + assert compare(exp(x + exp(-x)), exp(-x), x) == 0 + assert compare(exp(-x), x, x) > 0 + assert compare(x, exp(-x), x) < 0 + assert compare(exp(x + 1/x), x, x) > 0 + assert compare(exp(-exp(x)), exp(x), x) > 0 + assert compare(exp(exp(-exp(x)) + x), exp(-exp(x)), x) < 0 + + assert compare(exp(exp(x)), exp(x + exp(-exp(x))), x) > 0 def test_sign(): diff --git a/sympy/sets/fancysets.py b/sympy/sets/fancysets.py index de96d1e3b4c..f7e0af4a28f 100644 --- a/sympy/sets/fancysets.py +++ b/sympy/sets/fancysets.py @@ -398,7 +398,7 @@ def _contains(self, other): ((self.stop - other)/self.step).is_integer): return _sympify(other >= self.inf and other <= self.sup) elif (((self.start - other)/self.step).is_integer is False and - ((self.stop - other)/self.step).is_integer is False): + ((self.stop - other)/self.step).is_integer is False): return S.false def __iter__(self): diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py index 6aa2119d4dd..ed1957e2632 100644 --- a/sympy/sets/sets.py +++ b/sympy/sets/sets.py @@ -706,7 +706,7 @@ def __new__(cls, start, end, left_open=False, right_open=False): right_open = _sympify(right_open) if not all(isinstance(a, (type(true), type(false))) - for a in [left_open, right_open]): + for a in [left_open, right_open]): raise NotImplementedError( "left_open and right_open can have only true/false values, " "got %s and %s" % (left_open, right_open)) @@ -877,7 +877,6 @@ def _intersect(self, other): return Interval(start, end, left_open, right_open) - def _complement(self, other): if other is S.Reals: a = Interval(S.NegativeInfinity, self.start, @@ -887,7 +886,6 @@ def _complement(self, other): return Set._complement(self, other) - def _union(self, other): """ This function should only be used internally @@ -931,7 +929,7 @@ def _contains(self, other): return false if self.start is S.NegativeInfinity and self.end is S.Infinity: - if not other.is_extended_real is None: + if other.is_extended_real is not None: return other.is_extended_real if self.left_open: @@ -1489,7 +1487,7 @@ def reduce(A, B): return Intersection(s.complement(A) for s in B.args) result = B._complement(A) - if result != None: + if result is not None: return result else: return Complement(A, B, evaluate=False) @@ -1705,7 +1703,6 @@ def _complement(self, other): return Set._complement(self, other) - def _union(self, other): """ This function should only be used internally diff --git a/sympy/sets/tests/test_fancysets.py b/sympy/sets/tests/test_fancysets.py index 25d1189fed2..e5dfe892647 100644 --- a/sympy/sets/tests/test_fancysets.py +++ b/sympy/sets/tests/test_fancysets.py @@ -146,7 +146,7 @@ def test_Range(): assert Range(-1, 10, 1).intersect(S.Integers) == Range(-1, 10, 1) assert Range(-1, 10, 1).intersect(S.Naturals) == Range(1, 10, 1) - assert Range(1, 10, 1)._ith_element(5) == 6 # the index starts from zero + assert Range(1, 10, 1)._ith_element(5) == 6 # the index starts from zero assert Range(1, 10, 1)._last_element == 9 assert Range(1, 10, 1).boundary == Range(1, 10, 1) diff --git a/sympy/sets/tests/test_sets.py b/sympy/sets/tests/test_sets.py index 3e72aa4660f..d4ebc69cb41 100644 --- a/sympy/sets/tests/test_sets.py +++ b/sympy/sets/tests/test_sets.py @@ -30,7 +30,6 @@ def test_interval_arguments(): assert Interval(1, 1, True, False) == S.EmptySet assert Interval(1, 1, True, True) == S.EmptySet - assert isinstance(Interval(0, Symbol('a')), Interval) assert Interval(Symbol('a', extended_real=True, positive=True), 0) == S.EmptySet raises(ValueError, lambda: Interval(0, S.ImaginaryUnit)) @@ -41,7 +40,6 @@ def test_interval_arguments(): raises(NotImplementedError, lambda: Interval(0, 1, z, And(x, y))) - def test_interval_symbolic_end_points(): a = Symbol('a', extended_real=True) @@ -143,14 +141,14 @@ def test_Complement(): FiniteSet(2, 3, 4)), Interval(1, 3)) == \ Union(Interval(0, 1, False, True), FiniteSet(4)) - assert not 3 in Complement(Interval(0, 5), Interval(1, 4), evaluate=False) + assert 3 not in Complement(Interval(0, 5), Interval(1, 4), evaluate=False) assert -1 in Complement(S.Reals, S.Naturals, evaluate=False) - assert not 1 in Complement(S.Reals, S.Naturals, evaluate=False) + assert 1 not in Complement(S.Reals, S.Naturals, evaluate=False) assert Complement(S.Integers, S.UniversalSet) == EmptySet() assert S.UniversalSet.complement(S.Integers) == EmptySet() - assert (not 0 in S.Reals.intersect(S.Integers - FiniteSet(0))) + assert (0 not in S.Reals.intersect(S.Integers - FiniteSet(0))) assert S.EmptySet - S.Integers == S.EmptySet @@ -274,7 +272,6 @@ def test_intersection(): Intersection(S.Integers, S.Naturals, S.Reals, evaluate=False) - def test_is_disjoint(): assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False assert Interval(0, 2).is_disjoint(Interval(3, 4)) == True @@ -294,7 +291,7 @@ def test_interval_subs(): def test_interval_to_mpi(): assert Interval(0, 1).to_mpi() == mpi(0, 1) assert Interval(0, 1, True, False).to_mpi() == mpi(0, 1) - assert type(Interval(0, 1).to_mpi()) == type(mpi(0, 1)) + assert isinstance(Interval(0, 1).to_mpi(), type(mpi(0, 1))) def test_measure(): diff --git a/sympy/simplify/cse_opts.py b/sympy/simplify/cse_opts.py index 02d0b98e70f..a97de8156e9 100644 --- a/sympy/simplify/cse_opts.py +++ b/sympy/simplify/cse_opts.py @@ -35,7 +35,7 @@ def sub_post(e): replacements = [] for node in preorder_traversal(e): if isinstance(node, Mul) and \ - node.args[0] is S.One and node.args[1] is S.NegativeOne: + node.args[0] is S.One and node.args[1] is S.NegativeOne: replacements.append((node, -Mul._from_args(node.args[2:]))) for node, replacement in replacements: e = e.xreplace({node: replacement}) diff --git a/sympy/simplify/epathtools.py b/sympy/simplify/epathtools.py index 8728cfa422f..2b29bdb8c07 100644 --- a/sympy/simplify/epathtools.py +++ b/sympy/simplify/epathtools.py @@ -220,7 +220,8 @@ def _apply(path, expr, func): return expr.__class__(args) _args, _kwargs = args or (), kwargs or {} - _func = lambda expr: func(expr, *_args, **_kwargs) + def _func(expr): + return func(expr, *_args, **_kwargs) return _apply(self._epath, expr, _func) diff --git a/sympy/simplify/fu.py b/sympy/simplify/fu.py index 5873881e375..cd57d645e27 100644 --- a/sympy/simplify/fu.py +++ b/sympy/simplify/fu.py @@ -605,11 +605,9 @@ def TR8(rv, first=True): """ def f(rv): - if not ( - rv.is_Mul or - rv.is_Pow and - rv.base.func in (cos, sin) and - (rv.exp.is_integer or rv.base.is_positive)): + if not (rv.is_Mul or rv.is_Pow and + rv.base.func in (cos, sin) and + (rv.exp.is_integer or rv.base.is_positive)): return rv if first: @@ -775,7 +773,7 @@ def TR10(rv, first=True): """ def f(rv): - if not rv.func in (cos, sin): + if rv.func not in (cos, sin): return rv f = rv.func @@ -880,7 +878,7 @@ def do(rv, first=True): if n1 == n2: return gcd*cos(a - b) return gcd*cos(a + b) - else: #cossin, cossin + else: # cossin, cossin gcd = n1*gcd if n1 == n2: return gcd*sin(a + b) @@ -979,7 +977,7 @@ def TR11(rv, base=None): """ def f(rv): - if not rv.func in (cos, sin): + if rv.func not in (cos, sin): return rv if base: @@ -988,7 +986,7 @@ def f(rv): co = S.One if t.is_Mul: co, t = t.as_coeff_Mul() - if not t.func in (cos, sin): + if t.func not in (cos, sin): return rv if rv.args[0] == t.args[0]: c = cos(base) @@ -1536,9 +1534,8 @@ def TR111(rv): """ def f(rv): - if not ( - isinstance(rv, Pow) and - (rv.base.is_positive or rv.exp.is_integer and rv.exp.is_negative)): + if not (isinstance(rv, Pow) and + (rv.base.is_positive or rv.exp.is_integer and rv.exp.is_negative)): return rv if rv.base.func is tan: @@ -1941,7 +1938,7 @@ def pow_cos_sin(a, two): return return gcd, n1, n2, ca.args[0], sa.args[0], ca.func is sa.func if ca and sa or cb and sb or \ - two and (ca is None and sa is None or cb is None and sb is None): + two and (ca is None and sa is None or cb is None and sb is None): return c = ca or sa s = cb or sb diff --git a/sympy/simplify/hyperexpand.py b/sympy/simplify/hyperexpand.py index d32cfea10c3..b7d8766b8a0 100644 --- a/sympy/simplify/hyperexpand.py +++ b/sympy/simplify/hyperexpand.py @@ -558,7 +558,7 @@ def difficulty(self, func): diff = 0 for bucket, obucket in [(abuckets, oabuckets), (bbuckets, obbuckets)]: for mod in set(list(bucket.keys()) + list(obucket.keys())): - if (not mod in bucket) or (not mod in obucket) \ + if (mod not in bucket) or (mod not in obucket) \ or len(bucket[mod]) != len(obucket[mod]): return -1 l1 = list(bucket[mod]) @@ -760,7 +760,7 @@ def find_instantiations(self, func): for params in [self.func.ap, self.func.bq]] for bucket, obucket in [(abuckets, symb_a), (bbuckets, symb_b)]: for mod in set(list(bucket.keys()) + list(obucket.keys())): - if (not mod in bucket) or (not mod in obucket) \ + if (mod not in bucket) or (mod not in obucket) \ or len(bucket[mod]) != len(obucket[mod]): break for a, vals in zip(self.symbols, critical_values): @@ -786,8 +786,6 @@ def find_instantiations(self, func): return result - - class FormulaCollection(object): """ A collection of formulae to use as origins. """ @@ -835,7 +833,7 @@ def lookup_origin(self, func): return self.concrete_formulae[sizes][inv] # We don't have a concrete formula. Try to instantiate. - if not sizes in self.symbolic_formulae: + if sizes not in self.symbolic_formulae: return None # Too bad... possible = [] @@ -917,7 +915,7 @@ def __init__(self): def lookup_origin(self, func): """ Try to find a formula that matches func. """ - if not func.signature in self.formulae: + if func.signature not in self.formulae: return None for formula in self.formulae[func.signature]: res = formula.try_instantiate(func) @@ -1738,7 +1736,7 @@ def try_lerchphi(func): paired = {} for key, value in abuckets.items(): - if key != 0 and not key in bbuckets: + if key != 0 and key not in bbuckets: return None bvalue = bbuckets[key] paired[key] = (list(value), list(bvalue)) diff --git a/sympy/simplify/simplify.py b/sympy/simplify/simplify.py index 6214d014f77..b43644d6c66 100755 --- a/sympy/simplify/simplify.py +++ b/sympy/simplify/simplify.py @@ -55,7 +55,6 @@ import mpmath - def fraction(expr, exact=False): """Returns a pair with expression's numerator and denominator. If the given expression is not a fraction then this function @@ -1199,7 +1198,7 @@ def analyse_gens(gens, hints): trigdict = {} for (coeff, var), fn in trigterms: trigdict.setdefault(var, []).append((coeff, fn)) - res = [] # the ideal + res = [] # the ideal for key, val in trigdict.items(): # We have now assembeled a dictionary. Its keys are common @@ -2063,10 +2062,10 @@ def posify(eq): >>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True)) (_x + n + p, {_x: x}) - >> log(1/x).expand() # should be log(1/x) but it comes back as -log(x) + >> log(1/x).expand() # should be log(1/x) but it comes back as -log(x) log(1/x) - >>> log(posify(1/x)[0]).expand() # take [0] and ignore replacements + >>> log(posify(1/x)[0]).expand() # take [0] and ignore replacements -log(_x) >>> eq, rep = posify(1/x) >>> log(eq).expand().subs(rep) @@ -2398,7 +2397,7 @@ def powdenest(eq, force=False, polar=False): No other expansion is done. >>> i, j = symbols('i,j', integer=True) - >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j + >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j x**(x*(i + j)) But exp() will be denested by moving all non-log terms outside of @@ -2524,13 +2523,13 @@ def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops): But if an integer power of that radical has been autoexpanded then Mul does not join the resulting factors: - >>> a**4 # auto expands to a Mul, no longer a Pow + >>> a**4 # auto expands to a Mul, no longer a Pow x**2*y - >>> _*a # so Mul doesn't combine them + >>> _*a # so Mul doesn't combine them x**2*y*sqrt(x*sqrt(y)) - >>> powsimp(_) # but powsimp will + >>> powsimp(_) # but powsimp will (x*sqrt(y))**(5/2) - >>> powsimp(x*y*a) # but won't when doing so would violate assumptions + >>> powsimp(x*y*a) # but won't when doing so would violate assumptions x*y*sqrt(x*sqrt(y)) """ @@ -3023,7 +3022,6 @@ def eval(cls, a, b): return _rf(_a, b)*_rf(_a + c, -c)/_rf(_a + b + c, -c) - @timethis('combsimp') def combsimp(expr): r""" @@ -3081,7 +3079,6 @@ def combsimp(expr): # probably makes sense to retain them as_gamma = not expr.has(factorial, binomial) - expr = expr.replace(binomial, lambda n, k: _rf((n - k + 1).expand(), k.expand())/_rf(1, k.expand())) expr = expr.replace(factorial, @@ -3657,7 +3654,7 @@ def simplify(expr, ratio=1.7, measure=count_ops, fu=False): 8 >>> my_measure(h) 14 - >>> 15./8 > 1.7 # 1.7 is the default ratio + >>> 15./8 > 1.7 # 1.7 is the default ratio True >>> simplify(g, measure=my_measure) -log(a)*log(b) + log(a) + log(b) @@ -3908,7 +3905,7 @@ def nsimplify_real(x): expr = sympify(newexpr) if x and not expr: # don't let x become 0 raise ValueError - if expr.is_finite is False and not xv in [mpmath.inf, mpmath.ninf]: + if expr.is_finite is False and xv not in [mpmath.inf, mpmath.ninf]: raise ValueError return expr finally: @@ -4051,7 +4048,7 @@ def goodlog(l): # logs that have oppositely signed coefficients can divide for k in ordered(list(log1.keys())): - if not k in log1: # already popped as -k + if k not in log1: # already popped as -k continue if -k in log1: # figure out which has the minus sign; the one with @@ -4219,7 +4216,7 @@ def exp_trig(e): for ei in ex: e2 = ei**-2 if e2 in ex: - a = e2.args[0]/2 if not e2 is S.Exp1 else S.Half + a = e2.args[0]/2 if e2 is not S.Exp1 else S.Half newexpr = newexpr.subs((e2 + 1)*ei, 2*cosh(a)) newexpr = newexpr.subs((e2 - 1)*ei, 2*sinh(a)) ## exp ratios to tan and tanh @@ -4331,8 +4328,10 @@ def _futrig(e, **kwargs): else: coeff = S.One - Lops = lambda x: (L(x), x.count_ops(), _nodes(x), len(x.args), x.is_Add) - trigs = lambda x: x.has(TrigonometricFunction) + def Lops(x): + return (L(x), x.count_ops(), _nodes(x), len(x.args), x.is_Add) + def trigs(x): + return x.has(TrigonometricFunction) tree = [identity, ( @@ -4347,7 +4346,7 @@ def _futrig(e, **kwargs): TR14, # factored identities TR5, # sin-pow -> cos_pow TR10, # sin-cos of sums -> sin-cos prod - TR11, TR6, # reduce double angles and rewrite cos pows + TR11, TR6, # reduce double angles and rewrite cos pows lambda x: _eapply(factor, x, trigs), TR14, # factored powers of identities [identity, lambda x: _eapply(_mexpand, x, trigs)], @@ -4358,11 +4357,11 @@ def _futrig(e, **kwargs): [ lambda x: _eapply(expand_mul, TR5(x), trigs), lambda x: _eapply( - expand_mul, TR15(x), trigs)], # pos/neg powers of sin + expand_mul, TR15(x), trigs)], # pos/neg powers of sin [ lambda x: _eapply(expand_mul, TR6(x), trigs), lambda x: _eapply( - expand_mul, TR16(x), trigs)], # pos/neg powers of cos + expand_mul, TR16(x), trigs)], # pos/neg powers of cos TR111, # tan, sin, cos to neg power -> cot, csc, sec [identity, TR2i], # sin-cos ratio to tan [identity, lambda x: _eapply( @@ -4381,8 +4380,8 @@ def sum_simplify(s): from sympy.concrete.summations import Sum terms = Add.make_args(s) - s_t = [] # Sum Terms - o_t = [] # Other Terms + s_t = [] # Sum Terms + o_t = [] # Other Terms for term in terms: if isinstance(term, Mul): @@ -4464,8 +4463,8 @@ def product_simplify(s): from sympy.concrete.products import Product terms = Mul.make_args(s) - p_t = [] # Product Terms - o_t = [] # Other Terms + p_t = [] # Product Terms + o_t = [] # Other Terms for term in terms: if isinstance(term, Product): @@ -4794,9 +4793,12 @@ def _replace_mul_fpowxgpow(expr, f, g, rexp, h, rexph): return Mul(*args) -_idn = lambda x: x -_midn = lambda x: -x -_one = lambda x: S.One +def _idn(x): + return x +def _midn(x): + return -x +def _one(x): + return S.One def _match_div_rewrite(expr, i): """helper for __trigsimp""" diff --git a/sympy/simplify/tests/test_cse.py b/sympy/simplify/tests/test_cse.py index 8e51f06f736..86a75a11d44 100644 --- a/sympy/simplify/tests/test_cse.py +++ b/sympy/simplify/tests/test_cse.py @@ -145,7 +145,7 @@ def test_multiple_expressions(): ([(x0, x*y)], [x0, z + x0, 3 + x0*z]) -@XFAIL # CSE of non-commutative Mul terms is disabled +@XFAIL # CSE of non-commutative Mul terms is disabled def test_non_commutative_cse(): A, B, C = symbols('A B C', commutative=False) l = [A*B*C, A*C] @@ -165,7 +165,7 @@ def test_bypass_non_commutatives(): assert cse(l) == ([], l) -@XFAIL # CSE fails when replacing non-commutative sub-expressions +@XFAIL # CSE fails when replacing non-commutative sub-expressions def test_non_commutative_order(): A, B, C = symbols('A B C', commutative=False) x0 = symbols('x0', commutative=False) diff --git a/sympy/simplify/tests/test_epathtools.py b/sympy/simplify/tests/test_epathtools.py index d435d4f6f28..de6edb523cd 100644 --- a/sympy/simplify/tests/test_epathtools.py +++ b/sympy/simplify/tests/test_epathtools.py @@ -52,7 +52,8 @@ def test_epath_select(): def test_epath_apply(): expr = [((x, 1, t), 2), ((3, y, 4), z)] - func = lambda expr: expr**2 + def func(expr): + return expr**2 assert epath("/*", expr, list) == [[(x, 1, t), 2], [(3, y, 4), z]] diff --git a/sympy/simplify/tests/test_fu.py b/sympy/simplify/tests/test_fu.py index 5590604326a..fc96cf98624 100644 --- a/sympy/simplify/tests/test_fu.py +++ b/sympy/simplify/tests/test_fu.py @@ -69,7 +69,8 @@ def test_TR3(): def test__TR56(): - h = lambda x: 1 - x + def h(x): + return 1 - x assert T(sin(x)**3, sin, cos, h, 4, False) == sin(x)**3 assert T(sin(x)**10, sin, cos, h, 4, False) == sin(x)**10 assert T(sin(x)**6, sin, cos, h, 6, False) == (-cos(x)**2 + 1)**3 @@ -177,13 +178,12 @@ def test_TR10i(): assert TR10i(sqrt(2)*cos(x)*A + sqrt(6)*sin(x)*A) == \ 2*sqrt(2)*sin(x + pi/6)*A - c = cos(x) s = sin(x) h = sin(y) r = cos(y) for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)): - for a in ((c*r, s*h), (c*h, s*r)): # explicit 2-args + for a in ((c*r, s*h), (c*h, s*r)): # explicit 2-args args = zip(si, a) ex = Add(*[Mul(*ai) for ai in args]) t = TR10i(ex) @@ -194,7 +194,7 @@ def test_TR10i(): h = sin(pi/6) r = cos(pi/6) for si in ((1, 1), (1, -1), (-1, 1), (-1, -1)): - for a in ((c*r, s*h), (c*h, s*r)): # induced + for a in ((c*r, s*h), (c*h, s*r)): # induced args = zip(si, a) ex = Add(*[Mul(*ai) for ai in args]) t = TR10i(ex) @@ -242,11 +242,9 @@ def test_L(): def test_fu(): - assert fu(sin(50)**2 + cos(50)**2 + sin(pi/6)) == S(3)/2 assert fu(sqrt(6)*cos(x) + sqrt(2)*sin(x)) == 2*sqrt(2)*sin(x + pi/3) - eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2 assert fu(eq) == cos(x)**4 - 2*cos(y)**2 + 2 @@ -283,7 +281,8 @@ def test_objective(): def test_process_common_addends(): # this tests that the args are not evaluated as they are given to do # and that key2 works when key1 is False - do = lambda x: Add(*[i**(i%2) for i in x.args]) + def do(x): + return Add(*[i**(i%2) for i in x.args]) process_common_addends(Add(*[1, 2, 3, 4], evaluate=False), do, key2=lambda x: x%2, key1=False) == 1**1 + 3**1 + 2**0 + 4**0 diff --git a/sympy/simplify/tests/test_simplify.py b/sympy/simplify/tests/test_simplify.py index 8f67df7e3aa..b61a1ec241b 100644 --- a/sympy/simplify/tests/test_simplify.py +++ b/sympy/simplify/tests/test_simplify.py @@ -471,7 +471,7 @@ def test_simplify_expr(): assert simplify(A*B - B*A) == A*B - B*A assert simplify(A/(1 + y/x)) == x*A/(x + y) - assert simplify(A*(1/x + 1/y)) == A/x + A/y #(x + y)*A/(x*y) + assert simplify(A*(1/x + 1/y)) == A/x + A/y # (x + y)*A/(x*y) assert simplify(log(2) + log(3)) == log(6) assert simplify(log(2*x) - log(2)) == log(x) @@ -534,8 +534,10 @@ def test_simplify_ratio(): def test_simplify_measure(): - measure1 = lambda expr: len(str(expr)) - measure2 = lambda expr: -count_ops(expr) + def measure1(expr): + return len(str(expr)) + def measure2(expr): + return -count_ops(expr) # Return the most complicated result expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) assert measure1(simplify(expr, measure=measure1)) <= measure1(expr) @@ -1880,8 +1882,10 @@ def valid(a, b): def test_issue_2827_trigsimp_methods(): - measure1 = lambda expr: len(str(expr)) - measure2 = lambda expr: -count_ops(expr) + def measure1(expr): + return len(str(expr)) + def measure2(expr): + return -count_ops(expr) # Return the most complicated result expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) ans = Matrix([1]) @@ -1905,7 +1909,7 @@ def test_powsimp_on_numbers(): def test_inequality_no_auto_simplify(): # no simplify on creation but can be simplified lhs = cos(x)**2 + sin(x)**2 - rhs = 2; + rhs = 2 e = Lt(lhs, rhs) assert e == Lt(lhs, rhs, evaluate=False) assert simplify(e) diff --git a/sympy/solvers/bivariate.py b/sympy/solvers/bivariate.py index ea2162d07c8..6ed9de451ce 100644 --- a/sympy/solvers/bivariate.py +++ b/sympy/solvers/bivariate.py @@ -128,8 +128,8 @@ def _lambert(eq, x): return [] # violated assumptions other = -(-other).args[0] eq += other - if not x in other.free_symbols: - return [] # violated assumptions + if x not in other.free_symbols: + return [] # violated assumptions d, f, X2 = _linab(other, x) logterm = collect(eq - other, mainlog) a = logterm.as_coefficient(mainlog) diff --git a/sympy/solvers/deutils.py b/sympy/solvers/deutils.py index ca34e8786d7..d542089b538 100644 --- a/sympy/solvers/deutils.py +++ b/sympy/solvers/deutils.py @@ -247,7 +247,8 @@ def _desolve(eq, func=None, hint="default", ics=None, simplify=True, **kwargs): gethints.remove(i[:-len('_Integral')]) # special cases for k in ["1st_homogeneous_coeff_best", "1st_power_series", - "lie_group", "2nd_power_series_ordinary", "2nd_power_series_regular"]: + "lie_group", "2nd_power_series_ordinary", + "2nd_power_series_regular"]: if k in gethints: gethints.remove(k) for i in gethints: diff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py index 73f29b1be25..4c1b5e95db9 100644 --- a/sympy/solvers/diophantine.py +++ b/sympy/solvers/diophantine.py @@ -361,7 +361,7 @@ def diop_linear(eq, param=symbols("t", integer=True)): >>> from sympy.solvers.diophantine import diop_linear >>> from sympy.abc import x, y, z, t >>> from sympy import Integer - >>> diop_linear(2*x - 3*y - 5) #solves equation 2*x - 3*y -5 = 0 + >>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y -5 = 0 (-3*t - 5, -2*t - 5) Here x = -3*t - 5 and y = -2*t - 5 @@ -445,13 +445,13 @@ def base_solution_linear(c, a, b, t=None): >>> from sympy.solvers.diophantine import base_solution_linear >>> from sympy.abc import t - >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5 + >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5 (-5, 5) - >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0 + >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0 (0, 0) - >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5 + >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5 (3*t - 5, -2*t + 5) - >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0 + >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0 (7*t, -5*t) """ d = igcd(a, igcd(b, c)) @@ -460,7 +460,7 @@ def base_solution_linear(c, a, b, t=None): c = c // d if c == 0: - if t != None: + if t is not None: return (b*t , -a*t) else: return (S.Zero, S.Zero) @@ -471,7 +471,7 @@ def base_solution_linear(c, a, b, t=None): y0 = y0 * sign(b) if divisible(c, d): - if t != None: + if t is not None: return (c*x0 + b*t, c*y0 - a*t) else: return (Integer(c*x0), Integer(c*y0)) @@ -644,7 +644,6 @@ def _diop_quadratic(var, coeff, t): c = C // g e = sign(B/A) - if e*sqrt(c)*D - sqrt(a)*E == 0: z = symbols("z", extended_real=True) roots = solve(sqrt(a)*g*z**2 + D*z + sqrt(a)*F) @@ -653,11 +652,13 @@ def _diop_quadratic(var, coeff, t): l.add((diop_solve(sqrt(a)*x + e*sqrt(c)*y - root)[0], diop_solve(sqrt(a)*x + e*sqrt(c)*y - root)[1])) elif isinstance(e*sqrt(c)*D - sqrt(a)*E, Integer): - solve_x = lambda u: e*sqrt(c)*g*(sqrt(a)*E - e*sqrt(c)*D)*t**2 - (E + 2*e*sqrt(c)*g*u)*t\ - - (e*sqrt(c)*g*u**2 + E*u + e*sqrt(c)*F) // (e*sqrt(c)*D - sqrt(a)*E) + def solve_x(u): + return e*sqrt(c)*g*(sqrt(a)*E - e*sqrt(c)*D)*t**2 - (E + 2*e*sqrt(c)*g*u)*t \ + - (e*sqrt(c)*g*u**2 + E*u + e*sqrt(c)*F) // (e*sqrt(c)*D - sqrt(a)*E) - solve_y = lambda u: sqrt(a)*g*(e*sqrt(c)*D - sqrt(a)*E)*t**2 + (D + 2*sqrt(a)*g*u)*t \ - + (sqrt(a)*g*u**2 + D*u + sqrt(a)*F) // (e*sqrt(c)*D - sqrt(a)*E) + def solve_y(u): + return sqrt(a)*g*(e*sqrt(c)*D - sqrt(a)*E)*t**2 + (D + 2*sqrt(a)*g*u)*t \ + + (sqrt(a)*g*u**2 + D*u + sqrt(a)*F) // (e*sqrt(c)*D - sqrt(a)*E) for z0 in range(0, abs(e*sqrt(c)*D - sqrt(a)*E)): if divisible(sqrt(a)*g*z0**2 + D*z0 + sqrt(a)*F, e*sqrt(c)*D - sqrt(a)*E): @@ -693,18 +694,16 @@ def _diop_quadratic(var, coeff, t): l.add((x_0, y_0)) else: _var = var - _var[0], _var[1] = _var[1], _var[0] # Interchange x and y + _var[0], _var[1] = _var[1], _var[0] # Interchange x and y s = _diop_quadratic(_var, coeff, t) while len(s) > 0: sol = s.pop() l.add((sol[1], sol[0])) - # (5) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0 else: - P, Q = _transformation_to_DN(var, coeff) D, N = _find_DN(var, coeff) solns_pell = diop_DN(D, N) @@ -775,7 +774,6 @@ def _diop_quadratic(var, coeff, t): if is_solution_quad(var, coeff, x, y): done = True - x_n = S( (X_1 + sqrt(D)*Y_1)*(T + sqrt(D)*U)**(t*L) + (X_1 - sqrt(D)*Y_1)*(T - sqrt(D)*U)**(t*L) )/ 2 y_n = S( (X_1 + sqrt(D)*Y_1)*(T + sqrt(D)*U)**(t*L) - (X_1 - sqrt(D)*Y_1)*(T - sqrt(D)*U)**(t*L) )/ (2*sqrt(D)) @@ -787,7 +785,6 @@ def _diop_quadratic(var, coeff, t): if done: break - return l @@ -834,7 +831,7 @@ def diop_DN(D, N, t=symbols("t", integer=True)): ======== >>> from sympy.solvers.diophantine import diop_DN - >>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4 + >>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4 [(3, 1), (393, 109), (36, 10)] The output can be interpreted as follows: There are three fundamental @@ -842,7 +839,7 @@ def diop_DN(D, N, t=symbols("t", integer=True)): and (36, 10). Each tuple is in the form (x, y), i. e solution (3, 1) means that `x = 3` and `y = 1`. - >>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1 + >>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1 [(49299, 1570)] See Also @@ -883,7 +880,7 @@ def diop_DN(D, N, t=symbols("t", integer=True)): if isinstance(sqrt(N), Integer): return [(sqrt(N), t)] - else: # D > 0 + else: # D > 0 if isinstance(sqrt(D), Integer): r = sqrt(D) @@ -961,7 +958,7 @@ def diop_DN(D, N, t=symbols("t", integer=True)): if abs(m) != 2: zs = zs + [-i for i in zs] if S.Zero in zs: - zs.remove(S.Zero) # Remove duplicate zero + zs.remove(S.Zero) # Remove duplicate zero for z in zs: @@ -1010,9 +1007,9 @@ def cornacchia(a, b, m): ======== >>> from sympy.solvers.diophantine import cornacchia - >>> cornacchia(2, 3, 35) == {(2, 3), (4, 1)} # equation 2x**2 + 3y**2 = 35 + >>> cornacchia(2, 3, 35) == {(2, 3), (4, 1)} # equation 2x**2 + 3y**2 = 35 True - >>> cornacchia(1, 1, 25) == {(4, 3)} # equation x**2 + y**2 = 25 + >>> cornacchia(1, 1, 25) == {(4, 3)} # equation x**2 + y**2 = 25 True References @@ -1078,10 +1075,10 @@ def PQa(P_0, Q_0, D): ======== >>> from sympy.solvers.diophantine import PQa - >>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4 - >>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0) + >>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4 + >>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0) (13, 4, 3, 3, 1, -1) - >>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1) + >>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1) (-1, 1, 1, 4, 1, 3) References @@ -1163,7 +1160,6 @@ def diop_bf_DN(D, N, t=symbols("t", integer=True)): u = a[0][0] v = a[0][1] - if abs(N) == 1: return diop_DN(D, N) @@ -1186,7 +1182,6 @@ def diop_bf_DN(D, N, t=symbols("t", integer=True)): else: return [(S.Zero, S.Zero)] - for y in range(L1, L2): if isinstance(sqrt(N + D*y**2), Integer): x = sqrt(N + D*y**2) @@ -1258,9 +1253,9 @@ def length(P, Q, D): ======== >>> from sympy.solvers.diophantine import length - >>> length(-2 , 4, 5) # (-2 + sqrt(5))/4 + >>> length(-2 , 4, 5) # (-2 + sqrt(5))/4 3 - >>> length(-5, 4, 17) # (-5 + sqrt(17))/4 + >>> length(-5, 4, 17) # (-5 + sqrt(17))/4 4 """ x = P + sqrt(D) @@ -1333,10 +1328,10 @@ def transformation_to_DN(eq): >>> from sympy.abc import X, Y >>> from sympy import Matrix, simplify, Subs - >>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x + >>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x >>> u X/26 + 3*Y/26 - 6/13 - >>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y + >>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y >>> v Y/13 - 4/13 @@ -1368,7 +1363,6 @@ def transformation_to_DN(eq): http://www.jpr2718.org/ax2p.pdf """ - var, coeff, diop_type = classify_diop(eq) if diop_type == "binary_quadratic": return _transformation_to_DN(var, coeff) @@ -1659,7 +1653,7 @@ def _diop_ternary_quadratic(_var, coeff): X_0, y_0, z_0 = _diop_ternary_quadratic(var, _coeff) - if X_0 == None: + if X_0 is None: return (None, None, None) l = (S(B*y_0 + C*z_0)/(2*A)).q @@ -1787,7 +1781,7 @@ def simplified(x, y, z): """ Simplify the solution `(x, y, z)`. """ - if x == None or y == None or z == None: + if x is None or y is None or z is None: return (x, y, z) g = igcd(x, igcd(y, z)) @@ -1840,7 +1834,7 @@ def _parametrize_ternary_quadratic(solution, _var, coeff): v = [x]*3 v[0], v[1], v[2] = _var[0], _var[1], _var[2] - if x_0 == None: + if x_0 is None: return (None, None, None) if x_0 == 0: @@ -1861,7 +1855,6 @@ def _parametrize_ternary_quadratic(solution, _var, coeff): eq_1 = _mexpand(eq_1) A, B = eq_1.as_independent(r, as_Add=True) - x = A*x_0 y = (A*y_0 - _mexpand(B/r*p)) z = (A*z_0 - _mexpand(B/r*q)) @@ -1937,8 +1930,8 @@ def _diop_ternary_quadratic_normal(var, coeff): if A < 0 and B < 0: return (None, None, None) - if (sqrt_mod(-b_2*c_2, a_2) == None or sqrt_mod(-c_2*a_2, b_2) == None or - sqrt_mod(-a_2*b_2, c_2) == None): + if (sqrt_mod(-b_2*c_2, a_2) is None or sqrt_mod(-c_2*a_2, b_2) is None or + sqrt_mod(-a_2*b_2, c_2) is None): return (None, None, None) z_0, x_0, y_0 = descent(A, B) @@ -2093,15 +2086,15 @@ def ldescent(A, B): ======== >>> from sympy.solvers.diophantine import ldescent - >>> ldescent(1, 1) # w^2 = x^2 + y^2 + >>> ldescent(1, 1) # w^2 = x^2 + y^2 (1, 1, 0) - >>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2 + >>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2 (2, -1, 0) This means that `x = -1, y = 0` and `w = 2` is a solution to the equation `w^2 = 4x^2 - 7y^2` - >>> ldescent(5, -1) # w^2 = 5x^2 - y^2 + >>> ldescent(5, -1) # w^2 = 5x^2 - y^2 (2, 1, -1) References @@ -2139,7 +2132,7 @@ def ldescent(A, B): B_0, d = sign(Q)*i, sqrt(abs(Q) // i) break - if B_0 != None: + if B_0 is not None: W, X, Y = ldescent(A, B_0) return simplified((-A*X + r*W), (r*X - W), Y*(B_0*d)) # In this module Descent will always be called with inputs which have solutions. @@ -2161,7 +2154,7 @@ def descent(A, B): ======== >>> from sympy.solvers.diophantine import descent - >>> descent(3, 1) # x**2 = 3*y**2 + z**2 + >>> descent(3, 1) # x**2 = 3*y**2 + z**2 (1, 0, 1) `(x, y, z) = (1, 0, 1)` is a solution to the above equation. @@ -2746,7 +2739,7 @@ def power_representation(n, p, k, zeros=False): ======== >>> from sympy.solvers.diophantine import power_representation - >>> f = power_representation(1729, 3, 2) # Represent 1729 as a sum of two cubes + >>> f = power_representation(1729, 3, 2) # Represent 1729 as a sum of two cubes >>> next(f) (12, 1) >>> next(f) diff --git a/sympy/solvers/inequalities.py b/sympy/solvers/inequalities.py index 0bdfe6b52b1..ab0542294b3 100644 --- a/sympy/solvers/inequalities.py +++ b/sympy/solvers/inequalities.py @@ -463,7 +463,7 @@ def valid(x): def _solve_inequality(ie, s): """ A hacky replacement for solve, since the latter only works for univariate inequalities. """ - if not ie.rel_op in ('>', '>=', '<', '<='): + if ie.rel_op not in ('>', '>=', '<', '<='): raise NotImplementedError expr = ie.lhs - ie.rhs try: diff --git a/sympy/solvers/ode.py b/sympy/solvers/ode.py index f5f043e2c65..5ecef4dc598 100644 --- a/sympy/solvers/ode.py +++ b/sympy/solvers/ode.py @@ -381,7 +381,7 @@ def get_numbered_constants(eq, num=1, start=1, prefix='C'): def dsolve(eq, func=None, hint="default", simplify=True, - ics= None, xi=None, eta=None, x0=0, n=6, **kwargs): + ics= None, xi=None, eta=None, x0=0, n=6, **kwargs): r""" Solves any (supported) kind of ordinary differential equation and system of ordinary differential equations. @@ -502,8 +502,8 @@ def dsolve(eq, func=None, hint="default", simplify=True, - You can declare the derivative of an unknown function this way: >>> from sympy import Function, Derivative - >>> from sympy.abc import x # x is the independent variable - >>> f = Function("f")(x) # f is a function of x + >>> from sympy.abc import x # x is the independent variable + >>> f = Function("f")(x) # f is a function of x >>> # f_ will be the derivative of f with respect to x >>> f_ = Derivative(f, x) @@ -677,7 +677,8 @@ def _helper_simplify(eq, hint, match, simplify=True, **kwargs): # simplifications sols = solvefunc(eq, func, order, match) free = eq.free_symbols - cons = lambda s: s.free_symbols.difference(free) + def cons(s): + return s.free_symbols.difference(free) if isinstance(sols, Expr): return odesimp(sols, func, order, cons(sols), hint) return [odesimp(s, func, order, cons(s), hint) for s in sols] @@ -870,19 +871,19 @@ class in it. Note that a hint may do this anyway if deriv = funcarg.expr old = funcarg.variables[0] new = funcarg.point[0] - if isinstance(deriv, Derivative) and isinstance(deriv.args[0], - AppliedUndef) and deriv.args[0].func == f and old == x and not new.has(x): + if isinstance(deriv, Derivative) and \ + isinstance(deriv.args[0], AppliedUndef) and \ + deriv.args[0].func == f and old == x and not new.has(x): dorder = ode_order(deriv, x) temp = 'f' + str(dorder) boundary.update({temp: new, temp + 'val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Derivatives") - # Separating functions elif isinstance(funcarg, AppliedUndef): if funcarg.func == f and len(funcarg.args) == 1 and \ - not funcarg.args[0].has(x): + not funcarg.args[0].has(x): boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Function") @@ -965,10 +966,10 @@ class in it. Note that a hint may do this anyway if check = cancel(r[d]/r[e]) check1 = check.subs({x: point, y: value}) if not check1.has(oo) and not check1.has(zoo) and \ - not check1.has(NaN) and not check1.has(-oo): + not check1.has(NaN) and not check1.has(-oo): check2 = (check1.diff(x)).subs({x: point, y: value}) if not check2.has(oo) and not check2.has(zoo) and \ - not check2.has(NaN) and not check2.has(-oo): + not check2.has(NaN) and not check2.has(-oo): rseries = r.copy() rseries.update({'terms': terms, 'f0': point, 'f0val': value}) matching_hints["1st_power_series"] = rseries @@ -1141,7 +1142,6 @@ class in it. Note that a hint may do this anyway if matching_hints["almost_linear"] = r2 matching_hints["almost_linear_Integral"] = r2 - elif order == 2: # Liouville ODE in the form # f(x).diff(x, 2) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x) @@ -1177,10 +1177,10 @@ class in it. Note that a hint may do this anyway if point = kwargs.get('x0', 0) check = p.subs(x, point) if not check.has(oo) and not check.has(NaN) and \ - not check.has(zoo) and not check.has(-oo): + not check.has(zoo) and not check.has(-oo): check = q.subs(x, point) if not check.has(oo) and not check.has(NaN) and \ - not check.has(zoo) and not check.has(-oo): + not check.has(zoo) and not check.has(-oo): ordinary = True r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms}) matching_hints["2nd_power_series_ordinary"] = r @@ -1192,15 +1192,14 @@ class in it. Note that a hint may do this anyway if p = cancel((x - point)*p) check = p.subs(x, point) if not check.has(oo) and not check.has(NaN) and \ - not check.has(zoo) and not check.has(-oo): + not check.has(zoo) and not check.has(-oo): q = cancel(((x - point)**2)*q) check = q.subs(x, point) if not check.has(oo) and not check.has(NaN) and \ - not check.has(zoo) and not check.has(-oo): + not check.has(zoo) and not check.has(-oo): coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms} matching_hints["2nd_power_series_regular"] = coeff_dict - if order > 0: # nth order linear ODE # a_n(x)y^(n) + ... + a_1(x)y' + a_0(x)y = F(x) = b @@ -1262,7 +1261,6 @@ def _test_term(coeff, order): r['trialset'] = undetcoeff['trialset'] matching_hints["nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"] = r - # Order keys based on allhints. retlist = [i for i in allhints if i in matching_hints] @@ -1354,7 +1352,7 @@ def _sympify(eq): for eqs in eq: derivs = eqs.atoms(Derivative) func = set().union(*[d.atoms(AppliedUndef) for d in derivs]) - for func_ in func: + for func_ in func: order[func_] = 0 funcs.append(func_) funcs = list(set(funcs)) @@ -1451,7 +1449,7 @@ def linearity_check(eqs, j, func, is_linear_): elif matching_hints['no_of_equation'] == 3: if order_eq == 1: type_of_equation = check_linear_3eq_order1(eq, funcs, func_coef) - if type_of_equation==None: + if type_of_equation is None: type_of_equation = check_linear_neq_order1(eq, funcs, func_coef) else: type_of_equation = None @@ -1489,9 +1487,12 @@ def check_linear_2eq_order1(eq, func, func_coef): r = dict() # for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1) # and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2) - r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1] - r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1] - r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1] + r['a1'] = fc[0,x(t),1] + r['a2'] = fc[1,y(t),1] + r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] + r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1] + r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] + r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S(0), S(0)] for i in range(2): for j in Add.make_args(eq[i]): @@ -1535,8 +1536,10 @@ def check_linear_2eq_order1(eq, func, func_coef): # Equations for type 1 are Eq(a1*diff(x(t),t),b1*x(t)+c1*y(t)) and Eq(a2*diff(y(t),t),b2*x(t)+c2*y(t)) return "type1" else: - r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2'] - r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2'] + r['b1'] = r['b1']/r['a1'] + r['b2'] = r['b2']/r['a2'] + r['c1'] = r['c1']/r['a1'] + r['c2'] = r['c2']/r['a2'] if (r['b1'] == r['c2']) and (r['c1'] == r['b2']): # Equation for type 3 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), g(t)*x(t) + f(t)*y(t)) return "type3" @@ -1565,11 +1568,16 @@ def check_linear_2eq_order2(eq, func, func_coef): v = Wild('v', exclude=[t, t**2]) w = Wild('w', exclude=[t, t**2]) p = Wild('p', exclude=[t, t**2]) - r['a1'] = fc[0,x(t),2] ; r['a2'] = fc[1,y(t),2] - r['b1'] = fc[0,x(t),1] ; r['b2'] = fc[1,x(t),1] - r['c1'] = fc[0,y(t),1] ; r['c2'] = fc[1,y(t),1] - r['d1'] = fc[0,x(t),0] ; r['d2'] = fc[1,x(t),0] - r['e1'] = fc[0,y(t),0] ; r['e2'] = fc[1,y(t),0] + r['a1'] = fc[0,x(t),2] + r['a2'] = fc[1,y(t),2] + r['b1'] = fc[0,x(t),1] + r['b2'] = fc[1,x(t),1] + r['c1'] = fc[0,y(t),1] + r['c2'] = fc[1,y(t),1] + r['d1'] = fc[0,x(t),0] + r['d2'] = fc[1,x(t),0] + r['e1'] = fc[0,y(t),0] + r['e2'] = fc[1,y(t),0] const = [S(0), S(0)] for i in range(2): for j in Add.make_args(eq[i]): @@ -1583,7 +1591,8 @@ def check_linear_2eq_order2(eq, func, func_coef): return "type2" elif all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2 d1 d2 e1 e1'.split()): - p = [S(0), S(0)] ; q = [S(0), S(0)] + p = [S(0), S(0)] + q = [S(0), S(0)] for n, e in enumerate([r['f1'], r['f2']]): if e.has(t): tpart = e.as_independent(t, Mul)[1] @@ -1658,10 +1667,18 @@ def check_linear_3eq_order1(eq, func, func_coef): fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] r = dict() - r['a1'] = fc[0,x(t),1]; r['a2'] = fc[1,y(t),1]; r['a3'] = fc[2,z(t),1] - r['b1'] = fc[0,x(t),0]; r['b2'] = fc[1,x(t),0]; r['b3'] = fc[2,x(t),0] - r['c1'] = fc[0,y(t),0]; r['c2'] = fc[1,y(t),0]; r['c3'] = fc[2,y(t),0] - r['d1'] = fc[0,z(t),0]; r['d2'] = fc[1,z(t),0]; r['d3'] = fc[2,z(t),0] + r['a1'] = fc[0,x(t),1] + r['a2'] = fc[1,y(t),1] + r['a3'] = fc[2,z(t),1] + r['b1'] = fc[0,x(t),0] + r['b2'] = fc[1,x(t),0] + r['b3'] = fc[2,x(t),0] + r['c1'] = fc[0,y(t),0] + r['c2'] = fc[1,y(t),0] + r['c3'] = fc[2,y(t),0] + r['d1'] = fc[0,z(t),0] + r['d2'] = fc[1,z(t),0] + r['d3'] = fc[2,z(t),0] forcing = [S(0), S(0), S(0)] for i in range(3): for j in Add.make_args(eq[i]): @@ -1931,7 +1948,7 @@ def _sympify(eq): for eq in eqs: derivs = eq.atoms(Derivative) func = set().union(*[d.atoms(AppliedUndef) for d in derivs]) - for func_ in func: + for func_ in func: funcs.append(func_) funcs = list(set(funcs)) if not all(isinstance(func, AppliedUndef) and len(func.args) == 1 for func in funcs)\ @@ -2022,7 +2039,7 @@ def odesimp(eq, func, order, constants, hint): >>> pprint(odesimp(eq, f(x), 1, {C1}, ... hint='1st_homogeneous_coeff_subs_indep_div_dep', use_unicode=False - ... )) #doctest: +SKIP + ... )) # doctest: +SKIP x --------- = C1 /f(x)\ @@ -2540,7 +2557,8 @@ def _recursive_walk(expr): if expr.func is Equality: lhs, rhs = [_recursive_walk(i) for i in expr.args] - f = lambda i: isinstance(i, Number) or i in Cs + def f(i): + return isinstance(i, Number) or i in Cs if lhs.func is Symbol and lhs in Cs: rhs, lhs = lhs, rhs if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol): @@ -2749,7 +2767,8 @@ def constant_renumber(expr, symbolname, startnumber, endnumber): # that to make sure that term ordering is not dependent on # the indexed value of C C_1 = [(ci, S.One) for ci in constantsymbols] - sort_key=lambda arg: default_sort_key(arg.subs(C_1)) + def sort_key(arg): + return default_sort_key(arg.subs(C_1)) def _constant_renumber(expr): r""" @@ -3316,7 +3335,7 @@ def ode_Bernoulli(eq, func, order, match): d n P(x)*f(x) + --(f(x)) = Q(x)*f (x) dx - >>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral'), use_unicode=False) #doctest: +SKIP + >>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral'), use_unicode=False) # doctest: +SKIP 1 ---- 1 - n @@ -3648,7 +3667,6 @@ def ode_2nd_power_series_ordinary(eq, func, order, match): return Eq(f(x), series) - def ode_2nd_power_series_regular(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential @@ -3732,8 +3750,8 @@ def ode_2nd_power_series_regular(eq, func, order, match): p0, q0 = indicial sollist = solve(m*(m - 1) + m*p0 + q0, m) - if sollist and isinstance(sollist, list) and all( - [sol.is_extended_real for sol in sollist]): + if sollist and isinstance(sollist, list) and \ + all(sol.is_extended_real for sol in sollist): serdict1 = {} serdict2 = {} if len(sollist) == 1: @@ -4610,7 +4628,7 @@ def ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match, global collectterms collectterms = [] gensols = [] - conjugate_roots = [] # used to prevent double-use of conjugate roots + conjugate_roots = [] # used to prevent double-use of conjugate roots for root, multiplicity in charroots.items(): for i in range(multiplicity): if isinstance(root, RootOf): @@ -5388,11 +5406,10 @@ def ode_lie_group(eq, func, order, match): else: return [Eq(f(x), sol) for sol in sdeq] - - elif denom: # (ds/dr) is zero which means s is constant + elif denom: # (ds/dr) is zero which means s is constant return Eq(f(x), solve(scoord - C1, y)[0]) - elif num: # (dr/ds) is zero which means r is constant + elif num: # (dr/ds) is zero which means r is constant return Eq(f(x), solve(rcoord - C1, y)[0]) # If nothing works, return solution as it is, without solving for y @@ -5748,7 +5765,6 @@ def lie_heuristic_abaco1_product(match, comp=False): xi = Function('xi')(x, func) eta = Function('eta')(x, func) - inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y]) if inf and inf['coeff']: fx = inf[x] @@ -6551,7 +6567,8 @@ def _linear_2eq_order1_type2(x, y, t, r): .. math:: y = kx + (c_2 - c_1 k) t """ - r['k1'] = -r['k1']; r['k2'] = -r['k2'] + r['k1'] = -r['k1'] + r['k2'] = -r['k2'] if (r['a']*r['d'] - r['b']*r['c']) != 0: x0, y0 = symbols('x0, y0', cls=Dummy) sol = solve((r['a']*x0+r['b']*y0+r['k1'], r['c']*x0+r['d']*y0+r['k2']), x0, y0) @@ -6762,7 +6779,7 @@ def _linear_2eq_order1_type7(x, y, t, r): sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs else: - x0, y0 = symbols('x0, y0') #x0 and y0 being particular solutions + x0, y0 = symbols('x0, y0') # x0 and y0 being particular solutions F = exp(Integral(r['a'],t)) P = exp(Integral(r['d'],t)) sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t) @@ -6786,10 +6803,14 @@ def sysode_linear_2eq_order2(match_): eq[i] = eqs # for equations Eq(diff(x(t),t,t), a1*diff(x(t),t)+b1*diff(y(t),t)+c1*x(t)+d1*y(t)+e1) # and Eq(a2*diff(y(t),t,t), a2*diff(x(t),t)+b2*diff(y(t),t)+c2*x(t)+d2*y(t)+e2) - r['a1'] = -fc[0,x(t),1]/fc[0,x(t),2] ; r['a2'] = -fc[1,x(t),1]/fc[1,y(t),2] - r['b1'] = -fc[0,y(t),1]/fc[0,x(t),2] ; r['b2'] = -fc[1,y(t),1]/fc[1,y(t),2] - r['c1'] = -fc[0,x(t),0]/fc[0,x(t),2] ; r['c2'] = -fc[1,x(t),0]/fc[1,y(t),2] - r['d1'] = -fc[0,y(t),0]/fc[0,x(t),2] ; r['d2'] = -fc[1,y(t),0]/fc[1,y(t),2] + r['a1'] = -fc[0,x(t),1]/fc[0,x(t),2] + r['a2'] = -fc[1,x(t),1]/fc[1,y(t),2] + r['b1'] = -fc[0,y(t),1]/fc[0,x(t),2] + r['b2'] = -fc[1,y(t),1]/fc[1,y(t),2] + r['c1'] = -fc[0,x(t),0]/fc[0,x(t),2] + r['c2'] = -fc[1,x(t),0]/fc[1,y(t),2] + r['d1'] = -fc[0,y(t),0]/fc[0,x(t),2] + r['d2'] = -fc[1,y(t),0]/fc[1,y(t),2] const = [S(0), S(0)] for i in range(2): for j in Add.make_args(eq[i]): @@ -7001,7 +7022,8 @@ def _linear_2eq_order2_type3(x, y, t, r): """ C1, C2, C3, C4 = symbols('C1:5') if r['b1']**2 - 4*r['c1'] > 0: - r['a'] = r['b1'] ; r['b'] = -r['c1'] + r['a'] = r['b1'] + r['b'] = -r['c1'] alpha = r['a']/2 + sqrt(r['a']**2 + 4*r['b'])/2 beta = r['a']/2 - sqrt(r['a']**2 + 4*r['b'])/2 sol1 = C1*cos(alpha*t) + C2*sin(alpha*t) + C3*cos(beta*t) + C4*sin(beta*t) @@ -7057,10 +7079,14 @@ def _linear_2eq_order2_type4(x, y, t, r): C1, C2, C3, C4 = symbols('C1:5') k = Symbol('k') Ra, Ca, Rb, Cb = symbols('Ra, Ca, Rb, Cb') - a1 = r['a1'] ; a2 = r['a2'] - b1 = r['b1'] ; b2 = r['b2'] - c1 = r['c1'] ; c2 = r['c2'] - d1 = r['d1'] ; d2 = r['d2'] + a1 = r['a1'] + a2 = r['a2'] + b1 = r['b1'] + b2 = r['b2'] + c1 = r['c1'] + c2 = r['c2'] + d1 = r['d1'] + d2 = r['d2'] k1 = r['e1'].expand().as_independent(t)[0] k2 = r['e2'].expand().as_independent(t)[0] ew1 = r['e1'].expand().as_independent(t)[1] @@ -7124,7 +7150,8 @@ def _linear_2eq_order2_type5(x, y, t, r): """ C1, C2, C3, C4 = symbols('C1:5') - r['a'] = -r['d1'] ; r['b'] = -r['c2'] + r['a'] = -r['d1'] + r['b'] = -r['c2'] mul = sqrt(abs(r['a']*r['b'])) if r['a']*r['b'] > 0: u = C1*r['a']*exp(mul*t**2/2) + C2*r['a']*exp(-mul*t**2/2) @@ -7320,10 +7347,14 @@ def _linear_2eq_order2_type9(x, y, t, r): """ C1, C2, C3, C4 = symbols('C1:5') k = Symbol('k') - a1 = -r['a1']*t; a2 = -r['a2']*t - b1 = -r['b1']*t; b2 = -r['b2']*t - c1 = -r['c1']*t**2; c2 = -r['c2']*t**2 - d1 = -r['d1']*t**2; d2 = -r['d2']*t**2 + a1 = -r['a1']*t + a2 = -r['a2']*t + b1 = -r['b1']*t + b2 = -r['b2']*t + c1 = -r['c1']*t**2 + c2 = -r['c2']*t**2 + d1 = -r['d1']*t**2 + d2 = -r['d2']*t**2 eq = (k**2+(a1-1)*k+c1)*(k**2+(b2-1)*k+d2)-(b1*k+d1)*(a2*k+c2) [k1, k2, k3, k4] = roots_quartic(Poly(eq)) sol1 = -C1*(b1*k1+d1)*exp(k1*log(t)) - C2*(b1*k2+d1)*exp(k2*log(t)) - \ @@ -7402,8 +7433,10 @@ def _linear_2eq_order2_type11(x, y, t, r): """ C1, C2, C3, C4 = symbols('C1:5') u, v = symbols('u, v', function=True) - f = -r['c1'] ; g = -r['d1'] - h = -r['c2'] ; p = -r['d2'] + f = -r['c1'] + g = -r['d1'] + h = -r['c2'] + p = -r['d2'] [msol1, msol2] = dsolve([Eq(diff(u(t),t), t*f*u(t) + t*g*v(t)), Eq(diff(v(t),t), t*h*u(t) + t*p*v(t))]) sol1 = C3*t + t*Integral(msol1.rhs/t**2, t) sol2 = C4*t + t*Integral(msol2.rhs/t**2, t) @@ -7428,11 +7461,14 @@ def sysode_linear_3eq_order1(match_): # Eq(g1*diff(x(t),t), a1*x(t)+b1*y(t)+c1*z(t)+d1), # Eq(g2*diff(y(t),t), a2*x(t)+b2*y(t)+c2*z(t)+d2), and # Eq(g3*diff(z(t),t), a3*x(t)+b3*y(t)+c3*z(t)+d3) - r['a1'] = fc[0,x(t),0]/fc[0,x(t),1]; r['a2'] = fc[1,x(t),0]/fc[1,y(t),1]; + r['a1'] = fc[0,x(t),0]/fc[0,x(t),1] + r['a2'] = fc[1,x(t),0]/fc[1,y(t),1] r['a3'] = fc[2,x(t),0]/fc[2,z(t),1] - r['b1'] = fc[0,y(t),0]/fc[0,x(t),1]; r['b2'] = fc[1,y(t),0]/fc[1,y(t),1]; + r['b1'] = fc[0,y(t),0]/fc[0,x(t),1] + r['b2'] = fc[1,y(t),0]/fc[1,y(t),1] r['b3'] = fc[2,y(t),0]/fc[2,z(t),1] - r['c1'] = fc[0,z(t),0]/fc[0,x(t),1]; r['c2'] = fc[1,z(t),0]/fc[1,y(t),1]; + r['c1'] = fc[0,z(t),0]/fc[0,x(t),1] + r['c2'] = fc[1,z(t),0]/fc[1,y(t),1] r['c3'] = fc[2,z(t),0]/fc[2,z(t),1] forcing = [S(0), S(0), S(0)] for i in range(3): @@ -7484,8 +7520,12 @@ def _linear_3eq_order1_type1(x, y, z, t, r): """ C1, C2, C3, C4 = symbols('C1:5') - a = -r['a1']; b = -r['a2']; c = -r['b2'] - d = -r['a3']; k = -r['b3']; p = -r['c3'] + a = -r['a1'] + b = -r['a2'] + c = -r['b2'] + d = -r['a3'] + k = -r['b3'] + p = -r['c3'] sol1 = C1*exp(a*t) sol2 = b*C1*exp(a*t)/(a-c) + C2*exp(c*t) sol3 = C1*(d+b*k/(a-c))*exp(a*t)/(a-p) + k*C2*exp(c*t)/(c-p) + C3*exp(p*t) @@ -7526,7 +7566,9 @@ def _linear_3eq_order1_type2(x, y, z, t, r): """ C0, C1, C2, C3 = symbols('C0:4') - a = -r['c2']; b = -r['a3']; c = -r['b1'] + a = -r['c2'] + b = -r['a3'] + c = -r['b1'] k = sqrt(a**2 + b**2 + c**2) C3 = (-a*C1 - b*C2)/c sol1 = a*C0 + k*C1*cos(k*t) + (c*C2-b*C3)*sin(k*t) @@ -7605,8 +7647,10 @@ def _linear_3eq_order1_type4(x, y, z, t, r): u, v, w = symbols('u, v, w', function=True) a2, a3 = cancel(r['b1']/r['c1']).as_numer_denom() f = cancel(r['b1']/a2) - b1 = cancel(r['a2']/f); b3 = cancel(r['c2']/f) - c1 = cancel(r['a3']/f); c2 = cancel(r['b3']/f) + b1 = cancel(r['a2']/f) + b3 = cancel(r['c2']/f) + c1 = cancel(r['a3']/f) + c2 = cancel(r['b3']/f) a1, g = div(r['a1'],f) b2 = div(r['b2'],f)[0] c3 = div(r['c3'],f)[0] @@ -7920,8 +7964,10 @@ def _nonlinear_2eq_order1_type4(x, y, t, eq): R1 = num.match(f1*g1) R2 = denum.match(f2*g2) phi = (r1[f].subs(x(t),u).subs(y(t),v))/num - F1 = R1[f1]; F2 = R2[f2] - G1 = R1[g1]; G2 = R2[g2] + F1 = R1[f1] + F2 = R2[f2] + G1 = R1[g1] + G2 = R2[g2] sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u) sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v) sol = [] @@ -7977,7 +8023,8 @@ def check_type(x, y): if not (r1 and r2): [r1, r2] = check_type(y, x) x, y = y, x - x1 = diff(x(t),t); y1 = diff(y(t),t) + x1 = diff(x(t),t) + y1 = diff(y(t),t) return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))} def sysode_nonlinear_3eq_order1(match_): @@ -8163,7 +8210,9 @@ def _nonlinear_3eq_order1_type3(x, y, z, t, eq): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t),t) - eq[1]).match(p*r[F3] - r[s]*F1)) - a = r[p]; b = r[q]; c = r[s] + a = r[p] + b = r[q] + c = r[s] F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w) F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w) F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w) @@ -8222,7 +8271,9 @@ def _nonlinear_3eq_order1_type4(x, y, z, t, eq): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1)) - a = r[p]; b = r[q]; c = r[s] + a = r[p] + b = r[q] + c = r[s] F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w) F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w) F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w) @@ -8272,7 +8323,9 @@ def _nonlinear_3eq_order1_type5(x, y, t, eq): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t),t) - eq[1]).match(y(t)*(a*r[F3] - r[c]*F1))) - a = r[p]; b = r[q]; c = r[s] + a = r[p] + b = r[q] + c = r[s] F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w) F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w) F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w) diff --git a/sympy/solvers/pde.py b/sympy/solvers/pde.py index 52bc6dcd518..c1df28d5b48 100644 --- a/sympy/solvers/pde.py +++ b/sympy/solvers/pde.py @@ -724,7 +724,6 @@ def pde_1st_linear_variable_coeff(eq, func, order, match, solvefun): d = match[match['d']] e = -match[match['e']] - if not d: # To deal with cases like b*ux = e or c*uy = e if not (b and c): diff --git a/sympy/solvers/recurr.py b/sympy/solvers/recurr.py index 3b7e857d1ac..2a03b6213e9 100644 --- a/sympy/solvers/recurr.py +++ b/sympy/solvers/recurr.py @@ -305,7 +305,8 @@ def _delta(p, k): C = [ Symbol('C' + str(i)) for i in range(0, A) ] - g = lambda i: Add(*[ c*_delta(q, i) for c, q in zip(C, Q) ]) + def g(i): + return Add(*[ c*_delta(q, i) for c, q in zip(C, Q) ]) if homogeneous: E = [ g(i) for i in range(N + 1, U) ] diff --git a/sympy/solvers/solvers.py b/sympy/solvers/solvers.py index 9c170146ca2..eae7a121907 100644 --- a/sympy/solvers/solvers.py +++ b/sympy/solvers/solvers.py @@ -193,7 +193,6 @@ def checksol(f, symbol, sol=None, **flags): elif isinstance(f, Equality): f = f.lhs - f.rhs - if not f: return True @@ -990,7 +989,7 @@ def _sympified_list(w): p.is_Pow and not implicit or p.is_Function and not implicit) and p.func not in (re, im): continue - elif not p in seen: + elif p not in seen: seen.add(p) if p.free_symbols & symset: non_inverts.add(p) @@ -1359,7 +1358,7 @@ def _solve(f, *symbols, **flags): # first see if it really depends on symbol and whether there # is a linear solution f_num, sol = solve_linear(f, symbols=symbols) - if not symbol in f_num.free_symbols: + if symbol not in f_num.free_symbols: return [] elif f_num.is_Symbol: # no need to check but simplify if desired @@ -1794,7 +1793,7 @@ def _ok_syms(e, sort=False): result.remove(b) default_simplify = bool(failed) # rely on system-solvers to simplify - if flags.get('simplify', default_simplify): + if flags.get('simplify', default_simplify): for r in result: for k in r: r[k] = simplify(r[k]) @@ -1861,9 +1860,9 @@ def solve_linear(lhs, rhs=0, symbols=[], exclude=[]): >>> solve_linear(1/(1/x - 2)) (0, 0) - >>> 1/(1/x) # to SymPy, this looks like x ... + >>> 1/(1/x) # to SymPy, this looks like x ... x - >>> solve_linear(1/(1/x)) # so a solution is given + >>> solve_linear(1/(1/x)) # so a solution is given (x, 0) If x is allowed to cancel, then this appears linear, but this sort of @@ -1939,7 +1938,7 @@ def solve_linear(lhs, rhs=0, symbols=[], exclude=[]): all_zero = False if dn is S.NaN: break - if not xi in dn.free_symbols: + if xi not in dn.free_symbols: vi = -(nn.subs(xi, 0))/dn if dens is None: dens = _simple_dens(eq, symbols) @@ -2340,7 +2339,7 @@ def det_perm(M): for j in perm: fac.append(list[idx + j]) idx += n - term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7 + term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7 args.append(term if s else -term) s = not s return Add(*args) @@ -2391,9 +2390,11 @@ def inv_quick(M): from sympy.matrices import zeros if any(i.has(Symbol) for i in M): if all(i.has(Symbol) for i in M): - det = lambda _: det_perm(_) + def det(_): + return det_perm(_) else: - det = lambda _: det_minor(_) + def det(_): + return det_minor(_) else: return M.inv() n = M.rows diff --git a/sympy/solvers/tests/test_diophantine.py b/sympy/solvers/tests/test_diophantine.py index 7d9c0286010..9991c773acd 100644 --- a/sympy/solvers/tests/test_diophantine.py +++ b/sympy/solvers/tests/test_diophantine.py @@ -550,7 +550,6 @@ def test_assumptions(): assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)} - def check_solutions(eq): """ Determines whether solutions returned by diophantine() satisfy the original diff --git a/sympy/solvers/tests/test_ode.py b/sympy/solvers/tests/test_ode.py index d848403fe2f..ca4fd228890 100644 --- a/sympy/solvers/tests/test_ode.py +++ b/sympy/solvers/tests/test_ode.py @@ -684,8 +684,12 @@ def test_classify_sysode(): P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', function=True) x, y, z = symbols('x, y, z', Function=True) t = symbols('t') - x1 = diff(x(t),t) ; y1 = diff(y(t),t) ; z1 = diff(z(t),t) - x2 = diff(x(t),t,t) ; y2 = diff(y(t),t,t) ; z2 = diff(z(t),t,t) + x1 = diff(x(t),t) + y1 = diff(y(t),t) + z1 = diff(z(t),t) + x2 = diff(x(t),t,t) + y2 = diff(y(t),t,t) + z2 = diff(z(t),t,t) eq1 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol1 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -5*t, (1, x(t), 1): 0, (0, x(t), 1): 1, \ @@ -2183,7 +2187,7 @@ def test_exact_enhancement(): def test_separable_reduced(): f = Function('f') - x = Symbol('x') # BUG: if x is real, a more complex solution is returned! + x = Symbol('x') # BUG: if x is real, a more complex solution is returned! df = f(x).diff(x) eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', @@ -2467,7 +2471,7 @@ def test_series(): @slow def test_lie_group(): C1 = Symbol("C1") - x = Symbol("x") # assuming x is real generates an error! + x = Symbol("x") # assuming x is real generates an error! a, b, c = symbols("a b c") eq = f(x).diff(x)**2 sol = dsolve(eq, f(x), hint='lie_group') @@ -2506,7 +2510,7 @@ def test_lie_group(): def test_user_infinitesimals(): C2 = Symbol("C2") - x = Symbol("x") # assuming x is real generates an error + x = Symbol("x") # assuming x is real generates an error eq = x*(f(x).diff(x)) + 1 - f(x)**2 sol = dsolve(eq, hint='lie_group', xi=sqrt(f(x) - 1)/sqrt(f(x) + 1), eta=0) @@ -2580,7 +2584,7 @@ def test_2nd_power_series_regular(): assert dsolve(eq) == Eq(f(x), C2*(-x**4/2 + 1) + C1*x**2 + O(x**6)) def test_issue_7093(): - x = Symbol("x") # assuming x is real leads to an error + x = Symbol("x") # assuming x is real leads to an error sol = Eq(f(x), C1 - 2*x*sqrt(x**3)/5) eq = Derivative(f(x), x)**2 - x**3 assert dsolve(eq) == sol and checkodesol(eq, sol) == (True, 0) diff --git a/sympy/solvers/tests/test_polysys.py b/sympy/solvers/tests/test_polysys.py index 4417b1a1e5e..7c108941718 100644 --- a/sympy/solvers/tests/test_polysys.py +++ b/sympy/solvers/tests/test_polysys.py @@ -62,7 +62,8 @@ def test_solve_biquadratic(): [(1 - sqrt(((2*r - 1)*(2*r + 1)))/2, S(3)/2), (1 + sqrt(((2*r - 1)*(2*r + 1)))/2, S(3)/2)] - query = lambda expr: expr.is_Pow and expr.exp is S.Half + def query(expr): + return expr.is_Pow and expr.exp is S.Half f_1 = (x - 1 )**2 + (y - 2)**2 - r**2 f_2 = (x - x1)**2 + (y - 1)**2 - r**2 diff --git a/sympy/solvers/tests/test_solvers.py b/sympy/solvers/tests/test_solvers.py index 2f716189b18..869c2348aae 100644 --- a/sympy/solvers/tests/test_solvers.py +++ b/sympy/solvers/tests/test_solvers.py @@ -248,7 +248,6 @@ def test_quintics_1(): RootOf(x**5 + 3*x**3 + 7, 0).n() - def test_highorder_poly(): # just testing that the uniq generator is unpacked sol = solve(x**6 - 2*x + 2) @@ -1039,7 +1038,7 @@ def s_check(rv, ans): 102*2**(S(2)/3)*3**(S(5)/6)*s**5*I + 1620*s**4 - 1620*sqrt(3)*s**4*I - 13872*18**(S(1)/3)*s**3 + 471648*s - 471648*sqrt(3)*s*I, [s, s**3 - 306*x - sqrt(3)*sqrt(31212*x**2 - 165240*x + 61484) + 810])) - assert solve(eq) == [] # not other code errors + assert solve(eq) == [] # not other code errors @slow diff --git a/sympy/stats/crv_types.py b/sympy/stats/crv_types.py index 1e21973febb..4b4271793d2 100644 --- a/sympy/stats/crv_types.py +++ b/sympy/stats/crv_types.py @@ -91,7 +91,6 @@ ] - def ContinuousRV(symbol, density, set=Interval(-oo, oo)): """ Create a Continuous Random Variable given the following: @@ -2246,7 +2245,6 @@ def pdf(self, x): n - 1)*Sum((-1)**k*binomial(n, k)*(x - k)**(n - 1), (k, 0, floor(x))) - def UniformSum(name, n): r""" Create a continuous random variable with an Irwin-Hall distribution. diff --git a/sympy/stats/frv.py b/sympy/stats/frv.py index 7712bfe89be..1b750fbcb68 100644 --- a/sympy/stats/frv.py +++ b/sympy/stats/frv.py @@ -137,8 +137,6 @@ def __new__(cls, domain, condition): return Basic.__new__(cls, domain, cond) - - def _test(self, elem): val = self.condition.xreplace(dict(elem)) if val in [True, False]: diff --git a/sympy/stats/rv.py b/sympy/stats/rv.py index bbd932725a1..1da45664135 100644 --- a/sympy/stats/rv.py +++ b/sympy/stats/rv.py @@ -369,7 +369,7 @@ def sym_domain_dict(self): @property def symbols(self): return FiniteSet(*[sym for domain in self.domains - for sym in domain.symbols]) + for sym in domain.symbols]) @property def domains(self): diff --git a/sympy/stats/rv_interface.py b/sympy/stats/rv_interface.py index 728227dc661..49274134283 100644 --- a/sympy/stats/rv_interface.py +++ b/sympy/stats/rv_interface.py @@ -11,7 +11,6 @@ 'moment', 'cmoment', 'sampling_density'] - def moment(X, n, c=0, condition=None, **kwargs): """ Return the nth moment of a random expression about c i.e. E((X-c)**n) diff --git a/sympy/stats/tests/test_continuous_rv.py b/sympy/stats/tests/test_continuous_rv.py index c496b05bb38..cde6ccfd0c5 100644 --- a/sympy/stats/tests/test_continuous_rv.py +++ b/sympy/stats/tests/test_continuous_rv.py @@ -468,7 +468,6 @@ def test_uniform(): assert simplify(E(X)) == l + w/2 assert simplify(variance(X)) == w**2/12 - # With numbers all is well X = Uniform('x', 3, 5) assert P(X < 3) == 0 and P(X > 5) == 0 diff --git a/sympy/stats/tests/test_rv.py b/sympy/stats/tests/test_rv.py index 540b99e53a6..19764edeaea 100644 --- a/sympy/stats/tests/test_rv.py +++ b/sympy/stats/tests/test_rv.py @@ -71,8 +71,8 @@ def test_RandomSymbol(): assert X.name == X.symbol.name - X = Normal('lambda', 0, 1) # make sure we can use protected terms - X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms + X = Normal('lambda', 0, 1) # make sure we can use protected terms + X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms def test_RandomSymbol_diff(): @@ -120,7 +120,6 @@ def test_Sample(): # Make sure this doesn't raise an error E(Sum(1/z**Y, (z, 1, oo)), Y > 2, numsamples=3) - assert all(i in range(1, 7) for i in density(X, numsamples=10)) assert all(i in range(4, 7) for i in density(X, X>3, numsamples=10)) diff --git a/sympy/strategies/branch/core.py b/sympy/strategies/branch/core.py index 355ec5d55f8..6996217f727 100644 --- a/sympy/strategies/branch/core.py +++ b/sympy/strategies/branch/core.py @@ -54,7 +54,8 @@ def condition(cond, brule): """ Only apply branching rule if condition is true """ def conditioned_brl(expr): if cond(expr): - for x in brule(expr): yield x + for x in brule(expr): + yield x else: pass return conditioned_brl diff --git a/sympy/strategies/branch/tests/test_core.py b/sympy/strategies/branch/tests/test_core.py index 9b86e92b559..6434bfb7302 100644 --- a/sympy/strategies/branch/tests/test_core.py +++ b/sympy/strategies/branch/tests/test_core.py @@ -20,7 +20,8 @@ def branch5(x): else: yield x -even = lambda x: x%2 == 0 +def even(x): + return x%2 == 0 def inc(x): yield x + 1 @@ -91,7 +92,8 @@ def record(fn, input, output): assert L == [(2, 3)] def test_yieldify(): - inc = lambda x: x + 1 + def inc(x): + return x + 1 yinc = yieldify(inc) assert list(yinc(3)) == [4] diff --git a/sympy/strategies/core.py b/sympy/strategies/core.py index 61c25c50973..0088589a8c5 100644 --- a/sympy/strategies/core.py +++ b/sympy/strategies/core.py @@ -3,7 +3,8 @@ from sympy.core.compatibility import get_function_name -identity = lambda x: x +def identity(x): + return x def exhaust(rule): """ Apply a rule repeatedly until it has no effect """ @@ -32,7 +33,7 @@ def conditioned_rl(expr): if cond(expr): return rule(expr) else: - return expr + return expr return conditioned_rl def chain(*rules): @@ -95,8 +96,6 @@ def switch_rl(expr): return rl(expr) return switch_rl -identity = lambda x: x - def minimize(*rules, **kwargs): """ Select result of rules that minimizes objective diff --git a/sympy/strategies/tests/test_core.py b/sympy/strategies/tests/test_core.py index adafc9b8474..cc41cd75fd8 100644 --- a/sympy/strategies/tests/test_core.py +++ b/sympy/strategies/tests/test_core.py @@ -9,7 +9,7 @@ def rl(expr): safe_rl = null_safe(rl) assert rl(1) == safe_rl(1) - assert rl(3) == None + assert rl(3) == None assert safe_rl(3) == 3 def posdec(x): @@ -48,8 +48,10 @@ def test_do_one(): rl = do_one(posdec, posdec) assert rl(5) == 4 - rl1 = lambda x: 2 if x == 1 else x - rl2 = lambda x: 3 if x == 2 else x + def rl1(x): + return 2 if x == 1 else x + def rl2(x): + return 3 if x == 2 else x rule = do_one(rl1, rl2) assert rule(1) == 2 @@ -68,9 +70,12 @@ def test_debug(): assert '4' in log def test_switch(): - inc = lambda x: x + 1 - dec = lambda x: x - 1 - key = lambda x: x % 3 + def inc(x): + return x + 1 + def dec(x): + return x - 1 + def key(x): + return x % 3 rl = switch(key, {0: inc, 1: dec}) assert rl(3) == 4 @@ -78,8 +83,10 @@ def test_switch(): assert rl(5) == 5 def test_minimize(): - inc = lambda x: x + 1 - dec = lambda x: x - 1 + def inc(x): + return x + 1 + def dec(x): + return x - 1 rl = minimize(inc, dec) assert rl(4) == 3 diff --git a/sympy/strategies/tests/test_rl.py b/sympy/strategies/tests/test_rl.py index cdbeb53fa50..990d1563b2c 100644 --- a/sympy/strategies/tests/test_rl.py +++ b/sympy/strategies/tests/test_rl.py @@ -11,14 +11,17 @@ def test_rm_id(): def test_glom(): from sympy import Add from sympy.abc import x - key = lambda x: x.as_coeff_Mul()[1] - count = lambda x: x.as_coeff_Mul()[0] - newargs = lambda cnt, arg: cnt * arg + def key(x): + return x.as_coeff_Mul()[1] + def count(x): + return x.as_coeff_Mul()[0] + def newargs(cnt, arg): + return cnt * arg rl = glom(key, count, newargs) result = rl(Add(x, -x, 3*x, 2, 3, evaluate=False)) expected = Add(3*x, 5) - assert set(result.args) == set(expected.args) + assert set(result.args) == set(expected.args) def test_flatten(): assert flatten(Basic(1, 2, Basic(3, 4))) == Basic(1, 2, 3, 4) @@ -31,8 +34,10 @@ def test_sort(): assert sort(str)(Basic(3,1,2)) == Basic(1,2,3) def test_distribute(): - class T1(Basic): pass - class T2(Basic): pass + class T1(Basic): + pass + class T2(Basic): + pass distribute_t12 = distribute(T1, T2) assert distribute_t12(T1(1, 2, T2(3, 4), 5)) == \ diff --git a/sympy/strategies/tests/test_traverse.py b/sympy/strategies/tests/test_traverse.py index 203e3bc7604..b38953e5a4d 100644 --- a/sympy/strategies/tests/test_traverse.py +++ b/sympy/strategies/tests/test_traverse.py @@ -2,7 +2,8 @@ bottom_up_once, expr_fns, basic_fns) from sympy import Basic, symbols, Symbol, S -zero_symbols = lambda x: S.Zero if isinstance(x, Symbol) else x +def zero_symbols(x): + return S.Zero if isinstance(x, Symbol) else x x,y,z = symbols('x,y,z') def test_sall(): @@ -28,8 +29,10 @@ def _test_global_traversal(trav): def _test_stop_on_non_basics(trav): def add_one_if_can(expr): - try: return expr + 1 - except: return expr + try: + return expr + 1 + except: + return expr expr = Basic(1, 'a', Basic(2, 'b')) expected = Basic(2, 'a', Basic(3, 'b')) @@ -39,7 +42,8 @@ def add_one_if_can(expr): class Basic2(Basic): pass -rl = lambda x: Basic2(*x.args) if isinstance(x, Basic) else x +def rl(x): + return Basic2(*x.args) if isinstance(x, Basic) else x def test_top_down_once(): top_rl = top_down_once(rl) diff --git a/sympy/strategies/tests/test_tree.py b/sympy/strategies/tests/test_tree.py index 6b84780612e..9a049dabb5f 100644 --- a/sympy/strategies/tests/test_tree.py +++ b/sympy/strategies/tests/test_tree.py @@ -6,8 +6,10 @@ def test_treeapply(): tree = ([3, 3], [4, 1], 2) assert treeapply(tree, {list: min, tuple: max}) == 3 - add = lambda *args: sum(args) - mul = lambda *args: reduce(lambda a, b: a*b, args, 1) + def add(*args): + return sum(args) + def mul(*args): + return reduce(lambda a, b: a*b, args, 1) assert treeapply(tree, {list: add, tuple: mul}) == 60 def test_treeapply_leaf(): @@ -20,14 +22,17 @@ def test_treeapply_leaf(): def test_treeapply_strategies(): from sympy.strategies import chain, minimize join = {list: chain, tuple: minimize} - inc = lambda x: x + 1 - dec = lambda x: x - 1 - double = lambda x: 2*x + def inc(x): + return x + 1 + def dec(x): + return x - 1 + def double(x): + return 2*x assert treeapply(inc, join) == inc assert treeapply((inc, dec), join)(5) == minimize(inc, dec)(5) assert treeapply([inc, dec], join)(5) == chain(inc, dec)(5) - tree = (inc, [dec, double]) # either inc or dec-then-double + tree = (inc, [dec, double]) # either inc or dec-then-double assert treeapply(tree, join)(5) == 6 assert treeapply(tree, join)(1) == 0 @@ -38,10 +43,13 @@ def test_treeapply_strategies(): assert fn(1) == 2 # highest value comes from the inc def test_greedy(): - inc = lambda x: x + 1 - dec = lambda x: x - 1 - double = lambda x: 2*x - tree = [inc, (dec, double)] # either inc or dec-then-double + def inc(x): + return x + 1 + def dec(x): + return x - 1 + def double(x): + return 2*x + tree = [inc, (dec, double)] # either inc or dec-then-double fn = greedy(tree, objective=lambda x: -x) assert fn(4) == 6 # highest value comes from the dec then double @@ -55,10 +63,14 @@ def test_greedy(): assert highest(10) == 12 def test_allresults(): - inc = lambda x: x+1 - dec = lambda x: x-1 - double = lambda x: x*2 - square = lambda x: x**2 + def inc(x): + return x+1 + def dec(x): + return x-1 + def double(x): + return x*2 + def square(x): + return x**2 assert set(allresults(inc)(3)) == {inc(3)} assert set(allresults([inc, dec])(3)) == {2, 4} @@ -66,9 +78,12 @@ def test_allresults(): assert set(allresults([inc, (dec, double)])(4)) == {5, 6} def test_brute(): - inc = lambda x: x+1 - dec = lambda x: x-1 - square = lambda x: x**2 + def inc(x): + return x+1 + def dec(x): + return x-1 + def square(x): + return x**2 tree = ([inc, dec], square) fn = brute(tree, lambda x: -x) diff --git a/sympy/strategies/tree.py b/sympy/strategies/tree.py index 57757fd945c..36b225e44bc 100644 --- a/sympy/strategies/tree.py +++ b/sympy/strategies/tree.py @@ -5,7 +5,8 @@ import sympy.strategies.branch as branch from sympy.strategies.branch import yieldify -identity = lambda x: x +def identity(x): + return x def treeapply(tree, join, leaf=identity): """ Apply functions onto recursive containers (tree) diff --git a/sympy/tensor/tensor.py b/sympy/tensor/tensor.py index 22da2f5adb2..670871d0a63 100644 --- a/sympy/tensor/tensor.py +++ b/sympy/tensor/tensor.py @@ -371,10 +371,12 @@ def mul(f, g): >>> # This raises an exception: >>> # tids_1 * tids_4 """ - index_up = lambda u: u if u.is_up else -u + def index_up(u): + return u if u.is_up else -u # lambda returns True is index is not a matrix index: - notmat = lambda i: i not in (i._tensortype.auto_left, -i._tensortype.auto_right) + def notmat(i): + return i not in (i._tensortype.auto_left, -i._tensortype.auto_right) f_free = f.free[:] g_free = g.free[:] nc1 = len(f.components) @@ -728,7 +730,7 @@ def contract_metric(self, g): continue shifts[i] = shift free = [(ind, p, c - shifts[c]) for (ind, p, c) in free if c not in elim] - dum = [(p0, p1, c0 - shifts[c0], c1 - shifts[c1]) for i, (p0, p1, c0, c1) in enumerate(dum) if c0 not in elim and c1 not in elim] + dum = [(p0, p1, c0 - shifts[c0], c1 - shifts[c1]) for i, (p0, p1, c0, c1) in enumerate(dum) if c0 not in elim and c1 not in elim] components = [c for i, c in enumerate(components) if i not in elim] tids = TIDS(components, free, dum) return tids, sign @@ -3698,7 +3700,8 @@ def __call__(self, *indices): def _print(self): args = self.args - get_str = lambda arg: str(arg) if arg.is_Atom or isinstance(arg, TensExpr) else ("(%s)" % str(arg)) + def get_str(arg): + return str(arg) if arg.is_Atom or isinstance(arg, TensExpr) else ("(%s)" % str(arg)) if not args: # no arguments is equivalent to "1", i.e. TensMul(). @@ -3884,7 +3887,7 @@ def _join_lines(a): # if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1 # if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0 ta0 = dt[components[c0]] - b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0) + b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0) lines1 = lines[:] for line in lines: if line[-1] == b0: diff --git a/sympy/tensor/tests/test_tensor.py b/sympy/tensor/tests/test_tensor.py index 6cacd0a4eb2..a54f49a7851 100644 --- a/sympy/tensor/tests/test_tensor.py +++ b/sympy/tensor/tests/test_tensor.py @@ -358,7 +358,6 @@ def test_riemann_invariants(): # T_c = R^{d0 d1 d2 d3} * R_{d0 d1}^{d4 d5} * R_{d2 d3}^{d6 d7} * # R_{d4 d5}^{d8 d9} * R_{d6 d7}^{d10 d11} * R_{d8 d9 d10 d11} - t = R(-d11,d1,-d0,d5)*R(d6,d4,d0,-d5)*R(-d7,-d2,-d8,-d9)* \ R(-d10,-d3,-d6,-d4)*R(d2,d7,d11,-d1)*R(d8,d9,d3,d10) tc = t.canon_bp() @@ -463,7 +462,7 @@ def test_TensorIndexType(): i0, i1 = tensor_indices('i0 i1', TSpace) g = TSpace.metric A = tensorhead('A', [TSpace]*2, [[1]*2]) - assert str(A(i0,-i0).canon_bp()) == 'A(TSpace_0, -TSpace_0)' + assert str(A(i0,-i0).canon_bp()) == 'A(TSpace_0, -TSpace_0)' def test_indices(): Lorentz = TensorIndexType('Lorentz', dummy_fmt='L') @@ -810,7 +809,7 @@ def test_contract_metric1(): Lorentz = TensorIndexType('Lorentz', dummy_fmt='L') a, b = tensor_indices('a,b', Lorentz) g = Lorentz.metric - raises(ValueError, lambda: g(a, -a).contract_metric(g)) # no dim + raises(ValueError, lambda: g(a, -a).contract_metric(g)) # no dim def test_contract_metric2(): D = Symbol('D') diff --git a/sympy/tests/test_wester.py b/sympy/tests/test_wester.py index a285dbc7a96..f3427e5935d 100644 --- a/sympy/tests/test_wester.py +++ b/sympy/tests/test_wester.py @@ -868,7 +868,7 @@ def test_M7(): 1 - sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 - sqrt(-6 + 2*I*sqrt(3 + 4*sqrt(3)))/2, - 1 + sqrt(-6 + 2*I*sqrt(3 + 4*sqrt (3)))/2, + 1 + sqrt(-6 + 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 - sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2, 1 + sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2, 1 - sqrt(-6 - 2*sqrt(-3 + 4*sqrt(3)))/2, @@ -1181,7 +1181,7 @@ def test_N12(): def test_N13(): # raises NotImplementedError: can't reduce [sin(x) < 2] x = Symbol('x', extended_real=True) - assert solve(sin(x) < 2) == [] # S.Reals not found + assert solve(sin(x) < 2) == [] # S.Reals not found @XFAIL @@ -1290,15 +1290,15 @@ def test_P5(): M = Matrix([[7, 11], [3, 8]]) # Raises exception % not supported for matrices - assert M % 2 == Matrix([[1, 1], - [1, 0]]) + assert M % 2 == Matrix([[1, 1], + [1, 0]]) def test_P5_workaround(): M = Matrix([[7, 11], [3, 8]]) - assert M.applyfunc(lambda i: i % 2) == Matrix([[1, 1], - [1, 0]]) + assert M.applyfunc(lambda i: i % 2) == Matrix([[1, 1], + [1, 0]]) def test_P6(): @@ -1704,7 +1704,7 @@ def __my_jacobian(M, Y): def test_P44(): def __my_hessian(f, Y): V = Matrix([diff(f, v) for v in Y]) - return Matrix([V.T.diff(v) for v in Y]) + return Matrix([V.T.diff(v) for v in Y]) r, t = symbols('r t', extended_real=True) assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([ [ 2*sin(t), 2*r*cos(t)], @@ -1714,7 +1714,7 @@ def __my_hessian(f, Y): def test_P45(): def __my_wronskian(Y, v): M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))]) - return M.det() + return M.det() assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1 # Q1-Q6 Tensor tests missing @@ -1804,7 +1804,7 @@ def test_R7(): def test_R8(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(k**2*binomial(n, k), (k, 1, n)) - T = Sm.doit() #returns Piecewise function + T = Sm.doit() # returns Piecewise function # T.simplify() raisesAttributeError assert T.combsimp() == n*(n + 1)*2**(n - 2) @@ -2039,8 +2039,8 @@ def test_T4(): @slow def test_T5(): - assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 - + 2*exp(exp(3*x**3*log(x))))), x, oo) == Rational(1, 3) + assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 + + 2*exp(exp(3*x**3*log(x))))), x, oo) == Rational(1, 3) def test_T6(): diff --git a/sympy/utilities/autowrap.py b/sympy/utilities/autowrap.py index d6d52efd797..38504bfd4c3 100644 --- a/sympy/utilities/autowrap.py +++ b/sympy/utilities/autowrap.py @@ -447,9 +447,8 @@ def _validate_backend_language(backend, language): @cacheit @doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',)) -def autowrap( - expr, language=None, backend='f2py', tempdir=None, args=None, flags=None, - verbose=False, helpers=None): +def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None, + flags=None, verbose=False, helpers=None): """Generates python callable binaries based on the math expression. Parameters diff --git a/sympy/utilities/iterables.py b/sympy/utilities/iterables.py index 80cac74069a..94108a5fbdb 100644 --- a/sympy/utilities/iterables.py +++ b/sympy/utilities/iterables.py @@ -62,9 +62,11 @@ def flatten(iterable, levels=None, cls=None): "expected non-negative number of levels, got %s" % levels) if cls is None: - reducible = lambda x: is_sequence(x, set) + def reducible(x): + return is_sequence(x, set) else: - reducible = lambda x: isinstance(x, cls) + def reducible(x): + return isinstance(x, cls) result = [] @@ -847,7 +849,8 @@ def topological_sort(graph, key=None): S.discard(u) if key is None: - key = lambda value: value + def key(value): + return value S = sorted(S, key=key, reverse=True) diff --git a/sympy/utilities/lambdify.py b/sympy/utilities/lambdify.py index 5c3bc394d1f..c62df3d1eb9 100644 --- a/sympy/utilities/lambdify.py +++ b/sympy/utilities/lambdify.py @@ -393,7 +393,8 @@ def _issue_7853_dep_check(namespaces, namespace, expr): mat.__name__) == 'numpy.matrixlib.defmatrix.matrix'): return dicts = [m for m in namespaces if isinstance(m, dict)] - test = lambda expr: hasattr(expr, 'is_Matrix') and expr.is_Matrix + def test(expr): + return hasattr(expr, 'is_Matrix') and expr.is_Matrix if test(expr) and not [d for d in dicts if 'ImmutableMatrix' in d]: SymPyDeprecationWarning( "Currently, `sympy.Matrix` is replaced with `numpy.matrix` if " @@ -461,9 +462,11 @@ def lambdastr(args, expr, printer=None, dummify=False): lambdarepr = printer else: if inspect.isclass(printer): - lambdarepr = lambda expr: printer().doprint(expr) + def lambdarepr(expr): + return printer().doprint(expr) else: - lambdarepr = lambda expr: printer.doprint(expr) + def lambdarepr(expr): + return printer.doprint(expr) else: #XXX: This has to be done here because of circular imports from sympy.printing.lambdarepr import lambdarepr diff --git a/sympy/utilities/tests/test_codegen_octave.py b/sympy/utilities/tests/test_codegen_octave.py index 46f77da7036..f5220ffe998 100644 --- a/sympy/utilities/tests/test_codegen_octave.py +++ b/sympy/utilities/tests/test_codegen_octave.py @@ -195,7 +195,7 @@ def test_m_output_arg_mixed_unordered(): name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) result, = codegen(name_expr, "Octave", header=False, empty=False) assert result[0] == "foo.m" - source = result[1]; + source = result[1] expected = ( 'function [out1, y, out3, a] = foo(x)\n' ' out1 = cos(2*x);\n' @@ -250,7 +250,7 @@ def test_m_multifcns_per_file(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Octave", header=False, empty=False) assert result[0][0] == "foo.m" - source = result[0][1]; + source = result[0][1] expected = ( "function [out1, out2] = foo(x, y)\n" " out1 = 2*x;\n" @@ -268,7 +268,7 @@ def test_m_multifcns_per_file_w_header(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Octave", header=True, empty=False) assert result[0][0] == "foo.m" - source = result[0][1]; + source = result[0][1] expected = ( "function [out1, out2] = foo(x, y)\n" " %FOO Autogenerated by sympy\n" diff --git a/sympy/utilities/tests/test_enumerative.py b/sympy/utilities/tests/test_enumerative.py index 47663d14447..941a0e8f867 100644 --- a/sympy/utilities/tests/test_enumerative.py +++ b/sympy/utilities/tests/test_enumerative.py @@ -164,7 +164,7 @@ def subrange_exercise(mult, lb, ub): def test_subrange(): # Quick, but doesn't hit some of the corner cases - mult = [4,4,2,1] # mississippi + mult = [4,4,2,1] # mississippi lb = 1 ub = 2 subrange_exercise(mult, lb, ub) diff --git a/sympy/utilities/tests/test_iterables.py b/sympy/utilities/tests/test_iterables.py index 4b0a944abba..e46ac4d07b2 100644 --- a/sympy/utilities/tests/test_iterables.py +++ b/sympy/utilities/tests/test_iterables.py @@ -419,9 +419,9 @@ def test_partitions(): # (from pkrathmann2) for n in range(2, 6): - i = 0 - for m, q in _set_partitions(n): - assert q == RGS_unrank(i, n) + i = 0 + for m, q in _set_partitions(n): + assert q == RGS_unrank(i, n) i = i+1 assert i == RGS_enum(n) diff --git a/sympy/utilities/tests/test_lambdify.py b/sympy/utilities/tests/test_lambdify.py index 0b5837a975f..4fd26c0a4de 100644 --- a/sympy/utilities/tests/test_lambdify.py +++ b/sympy/utilities/tests/test_lambdify.py @@ -47,7 +47,8 @@ def test_str_args(): def test_own_namespace(): - myfunc = lambda x: 1 + def myfunc(x): + return 1 f = lambdify(x, sin(x), {"sin": myfunc}) assert f(0.1) == 1 assert f(100) == 1 @@ -168,7 +169,7 @@ def test_numexpr_printer(): from sympy import S blacklist = ('where', 'complex', 'contains') - arg_tuple = (x, y, z) # some functions take more than one argument + arg_tuple = (x, y, z) # some functions take more than one argument for sym in NumExprPrinter._numexpr_functions.keys(): if sym in blacklist: continue diff --git a/sympy/utilities/tests/test_pickling.py b/sympy/utilities/tests/test_pickling.py index 75ba93cc6be..20474283f47 100644 --- a/sympy/utilities/tests/test_pickling.py +++ b/sympy/utilities/tests/test_pickling.py @@ -346,7 +346,7 @@ def test_pickling_polys_rings(): check(c, exclude=[0, 1]) for c in (ring.dtype, ring.one): - check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k + check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k def test_pickling_polys_fields(): # NOTE: can't use protocols < 2 because we have to execute __new__ to diff --git a/sympy/utilities/timeutils.py b/sympy/utilities/timeutils.py index c0178693f85..08283a42c6e 100644 --- a/sympy/utilities/timeutils.py +++ b/sympy/utilities/timeutils.py @@ -55,7 +55,7 @@ def _print_timestack(stack, level=1): def timethis(name): def decorator(func): global _do_timings - if not name in _do_timings: + if name not in _do_timings: return func def wrapper(*args, **kwargs): diff --git a/sympy/vector/deloperator.py b/sympy/vector/deloperator.py index 3f534397f2d..cc4b82ef267 100644 --- a/sympy/vector/deloperator.py +++ b/sympy/vector/deloperator.py @@ -161,7 +161,6 @@ def __str__(self, printer=None): _sympystr = __str__ - def _diff_conditional(expr, base_scalar): """ First re-expresses expr in the system that base_scalar belongs to. diff --git a/sympy/vector/orienters.py b/sympy/vector/orienters.py index f2e81c803f7..5b10fd6829a 100644 --- a/sympy/vector/orienters.py +++ b/sympy/vector/orienters.py @@ -116,7 +116,7 @@ def __new__(cls, angle1, angle2, angle3, rot_order): rot_order = [i.replace('Y', '2') for i in rot_order] rot_order = [i.replace('Z', '3') for i in rot_order] rot_order = ''.join(rot_order) - if not rot_order in approved_orders: + if rot_order not in approved_orders: raise TypeError('Invalid rot_type parameter') a1 = int(rot_order[0]) a2 = int(rot_order[1]) diff --git a/sympy/vector/tests/test_functions.py b/sympy/vector/tests/test_functions.py index c93528f5217..bed4702663e 100644 --- a/sympy/vector/tests/test_functions.py +++ b/sympy/vector/tests/test_functions.py @@ -116,7 +116,6 @@ def test_express(): sin(q2)*cos(q1)*B.k), N).simplify() assert N.k == express((sin(q2)*B.j + cos(q2)*B.k), N).simplify() - assert A.i == express((cos(q1)*N.i + sin(q1)*N.j), A).simplify() assert A.j == express((-sin(q1)*N.i + cos(q1)*N.j), A).simplify() diff --git a/sympy/vector/vector.py b/sympy/vector/vector.py index 4f4835619f8..401036fef08 100755 --- a/sympy/vector/vector.py +++ b/sympy/vector/vector.py @@ -317,7 +317,7 @@ class BaseVector(Vector, AtomicExpr): def __new__(cls, name, index, system, pretty_str, latex_str): #Verify arguments - if not index in range(0, 3): + if index not in range(0, 3): raise ValueError("index must be 0, 1 or 2") if not isinstance(name, str): raise TypeError("name must be a valid string")