• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python iterables.sift函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sympy.utilities.iterables.sift函数的典型用法代码示例。如果您正苦于以下问题:Python sift函数的具体用法?Python sift怎么用?Python sift使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了sift函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: quantity_simplify

def quantity_simplify(expr):
    if expr.is_Atom:
        return expr
    if not expr.is_Mul:
        return expr.func(*map(quantity_simplify, expr.args))

    if expr.has(Prefix):
        coeff, args = expr.as_coeff_mul(Prefix)
        args = list(args)
        for arg in args:
            if isinstance(arg, Pow):
                coeff = coeff * (arg.base.scale_factor ** arg.exp)
            else:
                coeff = coeff * arg.scale_factor
        expr = coeff

    coeff, args = expr.as_coeff_mul(Quantity)
    args_pow = [arg.as_base_exp() for arg in args]
    quantity_pow, other_pow = sift(args_pow, lambda x: isinstance(x[0], Quantity), binary=True)
    quantity_pow_by_dim = sift(quantity_pow, lambda x: x[0].dimension)
    # Just pick the first quantity:
    ref_quantities = [i[0][0] for i in quantity_pow_by_dim.values()]
    new_quantities = [
        Mul.fromiter(
            (quantity*i.scale_factor/quantity.scale_factor)**p for i, p in v)
            if len(v) > 1 else v[0][0]**v[0][1]
        for quantity, (k, v) in zip(ref_quantities, quantity_pow_by_dim.items())]
    return coeff*Mul.fromiter(other_pow)*Mul.fromiter(new_quantities)
开发者ID:KonstantinTogoi,项目名称:sympy,代码行数:28,代码来源:util.py


示例2: _separate_imaginary_from_complex

    def _separate_imaginary_from_complex(cls, complexes):
        from sympy.utilities.iterables import sift

        def is_imag(c):
            '''
            return True if all roots are imaginary (ax**2 + b)
            return False if no roots are imaginary
            return None if 2 roots are imaginary (ax**N'''
            u, f, k = c
            deg = f.degree()
            if f.length() == 2:
                if deg == 2:
                    return True  # both imag
                elif _ispow2(deg):
                    if f.LC()*f.TC() < 0:
                        return None  # 2 are imag
            return False  # none are imag
        # separate according to the function
        sifted = sift(complexes, lambda c: c[1])
        del complexes
        imag = []
        complexes = []
        for f in sifted:
            isift = sift(sifted[f], lambda c: is_imag(c))
            imag.extend(isift.pop(True, []))
            complexes.extend(isift.pop(False, []))
            mixed = isift.pop(None, [])
            assert not isift
            if not mixed:
                continue
            while True:
                # the non-imaginary ones will be on one side or the other
                # of the y-axis
                i = 0
                while i < len(mixed):
                    u, f, k = mixed[i]
                    if u.ax*u.bx > 0:
                        complexes.append(mixed.pop(i))
                    else:
                        i += 1
                if len(mixed) == 2:
                    imag.extend(mixed)
                    break
                # refine
                for i, (u, f, k) in enumerate(mixed):
                    u = u._inner_refine()
                    mixed[i] = u, f, k
        return imag, complexes
开发者ID:A-turing-machine,项目名称:sympy,代码行数:48,代码来源:rootoftools.py


示例3: quantity_simplify

def quantity_simplify(expr):
    """Return an equivalent expression in which prefixes are replaced
    with numerical values and all units of a given dimension are the
    unified in a canonical manner.

    Examples
    ========

    >>> from sympy.physics.units.util import quantity_simplify
    >>> from sympy.physics.units.prefixes import kilo
    >>> from sympy.physics.units import foot, inch
    >>> quantity_simplify(kilo*foot*inch)
    250*foot**2/3
    >>> quantity_simplify(foot - 6*inch)
    foot/2
    """

    if expr.is_Atom or not expr.has(Prefix, Quantity):
        return expr

    # replace all prefixes with numerical values
    p = expr.atoms(Prefix)
    expr = expr.xreplace({p: p.scale_factor for p in p})

    # replace all quantities of given dimension with a canonical
    # quantity, chosen from those in the expression
    d = sift(expr.atoms(Quantity), lambda i: i.dimension)
    for k in d:
        if len(d[k]) == 1:
            continue
        v = list(ordered(d[k]))
        ref = v[0]/v[0].scale_factor
        expr = expr.xreplace({vi: ref*vi.scale_factor for vi in v[1:]})

    return expr
开发者ID:bjodah,项目名称:sympy,代码行数:35,代码来源:util.py


示例4: _ncsplit

 def _ncsplit(expr):
     # this is not the same as args_cnc because here
     # we don't assume expr is a Mul -- hence deal with args --
     # and always return a set.
     cpart, ncpart = sift(expr.args,
         lambda arg: arg.is_commutative is True, binary=True)
     return set(cpart), ncpart
开发者ID:bjodah,项目名称:sympy,代码行数:7,代码来源:operations.py


示例5: _eval_simplify

 def _eval_simplify(self, ratio, measure, rational, inverse):
     args = [a._eval_simplify(ratio, measure, rational, inverse)
         for a in self.args]
     for i, (expr, cond) in enumerate(args):
         # try to simplify conditions and the expression for
         # equalities that are part of the condition, e.g.
         # Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
         # -> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
         if isinstance(cond, And):
             eqs, other = sift(cond.args,
                 lambda i: isinstance(i, Equality), binary=True)
         elif isinstance(cond, Equality):
             eqs, other = [cond], []
         else:
             eqs = other = []
         if eqs:
             eqs = list(ordered(eqs))
             for j, e in enumerate(eqs):
                 # these blessed lhs objects behave like Symbols
                 # and the rhs are simple replacements for the "symbols"
                 if isinstance(e.lhs, (Symbol, UndefinedFunction)) and \
                     isinstance(e.rhs,
                         (Rational, NumberSymbol,
                         Symbol, UndefinedFunction)):
                     expr = expr.subs(*e.args)
                     eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
                     other = [ei.subs(*e.args) for ei in other]
             cond = And(*(eqs + other))
             args[i] = args[i].func(expr, cond)
     return self.func(*args)
开发者ID:cmarqu,项目名称:sympy,代码行数:30,代码来源:piecewise.py


示例6: _eval_expand_power_base

    def _eval_expand_power_base(self, deep=True, **hints):
        """(a*b)**n -> a**n * b**n"""
        force = hints.get("force", False)
        b, ewas = self.args
        if deep:
            e = self.exp.expand(deep=deep, **hints)
        else:
            e = self.exp
        if b.is_Mul:
            bargs = b.args
            if force or e.is_integer:
                nonneg = bargs
                other = []
            elif ewas.is_Rational or len(bargs) == 2 and bargs[0] is S.NegativeOne:
                # the Rational exponent was already expanded automatically
                # if there is a negative Number * foo, foo must be unknown
                #    or else it, too, would have automatically expanded;
                #    sqrt(-Number*foo) -> sqrt(Number)*sqrt(-foo); then
                #    sqrt(-foo) -> unchanged if foo is not positive else
                #               -> I*sqrt(foo)
                #    So...if we have a 2 arg Mul and the first is a Number
                #    that number is -1 and there is nothing more than can
                #    be done without the force=True hint
                nonneg = []
            else:
                # this is just like what is happening automatically, except
                # that now we are doing it for an arbitrary exponent for which
                # no automatic expansion is done
                def pred(x):
                    if x.is_polar is None:
                        return x.is_nonnegative
                    return x.is_polar

                sifted = sift(b.args, pred)
                nonneg = sifted.get(True, [])
                other = sifted.get(None, [])
                neg = sifted.get(False, [])

                # make sure the Number gets pulled out
                if neg and neg[0].is_Number and neg[0] is not S.NegativeOne:
                    nonneg.append(-neg[0])
                    neg[0] = S.NegativeOne

                # leave behind a negative sign
                oddneg = len(neg) % 2
                if oddneg:
                    other.append(S.NegativeOne)

                # negate all negatives and append to nonneg
                nonneg += [-n for n in neg]

            if nonneg:  # then there's a new expression to return
                other = [Pow(Mul(*other), e)]
                if deep:
                    return Mul(*([Pow(b.expand(deep=deep, **hints), e) for b in nonneg] + other))
                else:
                    return Mul(*([Pow(b, e) for b in nonneg] + other))
        return Pow(b, e)
开发者ID:kendhia,项目名称:sympy,代码行数:58,代码来源:power.py


示例7: conglomerate

 def conglomerate(expr):
     """ Conglomerate together identical args x + x -> 2x """
     groups = sift(expr.args, key)
     counts = dict((k, sum(map(count, args))) for k, args in groups.items())
     newargs = [combine(cnt, mat) for mat, cnt in counts.items()]
     if set(newargs) != set(expr.args):
         return new(type(expr), *newargs)
     else:
         return expr
开发者ID:archipleago-creature,项目名称:sympy,代码行数:9,代码来源:rl.py


示例8: __new__

 def __new__(cls, sym, condition, base_set=S.UniversalSet):
     # nonlinsolve uses ConditionSet to return an unsolved system
     # of equations (see _return_conditionset in solveset) so until
     # that is changed we do minimal checking of the args
     if isinstance(sym, (Tuple, tuple)):  # unsolved eqns syntax
         sym = Tuple(*sym)
         condition = FiniteSet(*condition)
         return Basic.__new__(cls, sym, condition, base_set)
     condition = as_Boolean(condition)
     if isinstance(base_set, set):
         base_set = FiniteSet(*base_set)
     elif not isinstance(base_set, Set):
         raise TypeError('expecting set for base_set')
     if condition is S.false:
         return S.EmptySet
     if condition is S.true:
         return base_set
     if isinstance(base_set, EmptySet):
         return base_set
     know = None
     if isinstance(base_set, FiniteSet):
         sifted = sift(
             base_set, lambda _: fuzzy_bool(
                 condition.subs(sym, _)))
         if sifted[None]:
             know = FiniteSet(*sifted[True])
             base_set = FiniteSet(*sifted[None])
         else:
             return FiniteSet(*sifted[True])
     if isinstance(base_set, cls):
         s, c, base_set = base_set.args
         if sym == s:
             condition = And(condition, c)
         elif sym not in c.free_symbols:
             condition = And(condition, c.xreplace({s: sym}))
         elif s not in condition.free_symbols:
             condition = And(condition.xreplace({sym: s}), c)
             sym = s
         else:
             # user will have to use cls.sym to get symbol
             dum = Symbol('lambda')
             if dum in condition.free_symbols or \
                     dum in c.free_symbols:
                 dum = Dummy(str(dum))
             condition = And(
                 condition.xreplace({sym: dum}),
                 c.xreplace({s: dum}))
             sym = dum
     if not isinstance(sym, Symbol):
         s = Dummy('lambda')
         if s not in condition.xreplace({sym: s}).free_symbols:
             raise ValueError(
                 'non-symbol dummy not recognized in condition')
     rv = Basic.__new__(cls, sym, condition, base_set)
     return rv if know is None else Union(know, rv)
开发者ID:asmeurer,项目名称:sympy,代码行数:55,代码来源:conditionset.py


示例9: _expm1_value

def _expm1_value(e):
    numbers, non_num = sift(e.args, lambda arg: arg.is_number, binary=True)
    non_num_exp, non_num_other = sift(non_num, lambda arg: arg.has(exp),
        binary=True)
    numsum = sum(numbers)
    new_exp_terms, done = [], False
    for exp_term in non_num_exp:
        if done:
            new_exp_terms.append(exp_term)
        else:
            looking_at = exp_term + numsum
            attempt = _try_expm1(looking_at)
            if looking_at == attempt:
                new_exp_terms.append(exp_term)
            else:
                done = True
                new_exp_terms.append(attempt)
    if not done:
        new_exp_terms.append(numsum)
    return e.func(*chain(new_exp_terms, non_num_other))
开发者ID:asmeurer,项目名称:sympy,代码行数:20,代码来源:rewriting.py


示例10: _eval_factor

 def _eval_factor(self, **hints):
     if 1 == len(self.limits):
         summand = self.function.factor(**hints)
         if summand.is_Mul:
             out = sift(summand.args, lambda w: w.is_commutative \
                 and not w.has(*self.variables))
             return C.Mul(*out[True])*self.func(C.Mul(*out[False]), \
                 *self.limits)
     else:
         summand = self.func(self.function, self.limits[0:-1]).factor()
         if not summand.has(self.variables[-1]):
             return self.func(1, [self.limits[-1]]).doit()*summand
         elif isinstance(summand, C.Mul):
             return self.func(summand, self.limits[-1]).factor()
     return self
开发者ID:Bercio,项目名称:sympy,代码行数:15,代码来源:expr_with_limits.py


示例11: __new__

 def __new__(cls, sym, condition, base_set):
     if condition == S.false:
         return S.EmptySet
     if condition == S.true:
         return base_set
     if isinstance(base_set, EmptySet):
         return base_set
     if isinstance(base_set, FiniteSet):
         sifted = sift(base_set, lambda _: fuzzy_bool(condition.subs(sym, _)))
         if sifted[None]:
             return Union(FiniteSet(*sifted[True]),
                          Basic.__new__(cls, sym, condition, FiniteSet(*sifted[None])))
         else:
             return FiniteSet(*sifted[True])
     return Basic.__new__(cls, sym, condition, base_set)
开发者ID:A-turing-machine,项目名称:sympy,代码行数:15,代码来源:conditionset.py


示例12: test_sift

def test_sift():
    assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]}
    assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]}
    assert sift([S.One], lambda _: _.has(x)) == {False: [1]}
    assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == (
        [1, 3], [0, 2])
    assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == (
        [1], [0, 2, 3])
    raises(ValueError, lambda:
        sift([0, 1, 2, 3], lambda x: x % 3, binary=True))
开发者ID:asmeurer,项目名称:sympy,代码行数:10,代码来源:test_iterables.py


示例13: cse_separate

def cse_separate(r, e):
    """Move expressions that are in the form (symbol, expr) out of the
    expressions and sort them into the replacements using the reps_toposort.

    Examples
    ========
    >>> from sympy.simplify.cse_main import cse_separate
    >>> from sympy.abc import x, y, z
    >>> from sympy import cos, exp, cse, Eq
    >>> eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))
    >>> cse([eq, Eq(x, z + 1), z - 2], postprocess=cse_separate)
    [[(x0, y + 1), (x, z + 1), (x1, x + 1)], [x1 + exp(x1/x0) + cos(x0), z - 2]]
    """
    syms = set([k for k, v in r])
    d = sift(e, lambda w: w.is_Equality and not bool(w.free_symbols & set(syms)))
    r, e = [r + [w.args for w in d[True]], d[False]]
    return [reps_toposort(r), e]
开发者ID:StefenYin,项目名称:sympy,代码行数:17,代码来源:cse_main.py


示例14: cse_separate

def cse_separate(r, e):
    """Move expressions that are in the form (symbol, expr) out of the
    expressions and sort them into the replacements using the reps_toposort.

    Examples
    ========
    >>> from sympy.simplify.cse_main import cse_separate
    >>> from sympy.abc import x, y, z
    >>> from sympy import cos, exp, cse, Eq, symbols
    >>> x0, x1 = symbols('x:2')
    >>> eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))
    >>> cse([eq, Eq(x, z + 1), z - 2], postprocess=cse_separate) in [
    ... [[(x0, y + 1), (x, z + 1), (x1, x + 1)],
    ...  [x1 + exp(x1/x0) + cos(x0), z - 2]],
    ... [[(x1, y + 1), (x, z + 1), (x0, x + 1)],
    ...  [x0 + exp(x0/x1) + cos(x1), z - 2]]]
    ...
    True
    """
    d = sift(e, lambda w: w.is_Equality and w.lhs.is_Symbol)
    r = r + [w.args for w in d[True]]
    e = d[False]
    return [reps_toposort(r), e]
开发者ID:Tkizzy,项目名称:PythonistaAppTemplate,代码行数:23,代码来源:cse_main.py


示例15: test_sift

def test_sift():
    assert sift(range(5), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]}
    assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]}
    assert sift([S.One], lambda _: _.has(x)) == {False: [1]}
开发者ID:Acebulf,项目名称:sympy,代码行数:4,代码来源:test_iterables.py


示例16: rule_gamma

    def rule_gamma(expr, level=0):
        """ Simplify products of gamma functions further. """

        if expr.is_Atom:
            return expr

        def gamma_rat(x):
            # helper to simplify ratios of gammas
            was = x.count(gamma)
            xx = x.replace(gamma, lambda n: _rf(1, (n - 1).expand()
                ).replace(_rf, lambda a, b: gamma(a + b)/gamma(a)))
            if xx.count(gamma) < was:
                x = xx
            return x

        def gamma_factor(x):
            # return True if there is a gamma factor in shallow args
            if isinstance(x, gamma):
                return True
            if x.is_Add or x.is_Mul:
                return any(gamma_factor(xi) for xi in x.args)
            if x.is_Pow and (x.exp.is_integer or x.base.is_positive):
                return gamma_factor(x.base)
            return False

        # recursion step
        if level == 0:
            expr = expr.func(*[rule_gamma(x, level + 1) for x in expr.args])
            level += 1

        if not expr.is_Mul:
            return expr

        # non-commutative step
        if level == 1:
            args, nc = expr.args_cnc()
            if not args:
                return expr
            if nc:
                return rule_gamma(Mul._from_args(args), level + 1)*Mul._from_args(nc)
            level += 1

        # pure gamma handling, not factor absorption
        if level == 2:
            T, F = sift(expr.args, gamma_factor, binary=True)
            gamma_ind = Mul(*F)
            d = Mul(*T)

            nd, dd = d.as_numer_denom()
            for ipass in range(2):
                args = list(ordered(Mul.make_args(nd)))
                for i, ni in enumerate(args):
                    if ni.is_Add:
                        ni, dd = Add(*[
                            rule_gamma(gamma_rat(a/dd), level + 1) for a in ni.args]
                            ).as_numer_denom()
                        args[i] = ni
                        if not dd.has(gamma):
                            break
                nd = Mul(*args)
                if ipass ==  0 and not gamma_factor(nd):
                    break
                nd, dd = dd, nd  # now process in reversed order
            expr = gamma_ind*nd/dd
            if not (expr.is_Mul and (gamma_factor(dd) or gamma_factor(nd))):
                return expr
            level += 1

        # iteration until constant
        if level == 3:
            while True:
                was = expr
                expr = rule_gamma(expr, 4)
                if expr == was:
                    return expr

        numer_gammas = []
        denom_gammas = []
        numer_others = []
        denom_others = []
        def explicate(p):
            if p is S.One:
                return None, []
            b, e = p.as_base_exp()
            if e.is_Integer:
                if isinstance(b, gamma):
                    return True, [b.args[0]]*e
                else:
                    return False, [b]*e
            else:
                return False, [p]

        newargs = list(ordered(expr.args))
        while newargs:
            n, d = newargs.pop().as_numer_denom()
            isg, l = explicate(n)
            if isg:
                numer_gammas.extend(l)
            elif isg is False:
                numer_others.extend(l)
#.........这里部分代码省略.........
开发者ID:KonstantinTogoi,项目名称:sympy,代码行数:101,代码来源:gammasimp.py


示例17: _matches_commutative

    def _matches_commutative(self, expr, repl_dict={}, old=False):
        """
        Matches Add/Mul "pattern" to an expression "expr".

        repl_dict ... a dictionary of (wild: expression) pairs, that get
                      returned with the results

        This function is the main workhorse for Add/Mul.

        For instance:

        >>> from sympy import symbols, Wild, sin
        >>> a = Wild("a")
        >>> b = Wild("b")
        >>> c = Wild("c")
        >>> x, y, z = symbols("x y z")
        >>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z)
        {a_: x, b_: y, c_: z}

        In the example above, "a+sin(b)*c" is the pattern, and "x+sin(y)*z" is
        the expression.

        The repl_dict contains parts that were already matched. For example
        here:

        >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x})
        {a_: x, b_: y, c_: z}

        the only function of the repl_dict is to return it in the
        result, e.g. if you omit it:

        >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z)
        {b_: y, c_: z}

        the "a: x" is not returned in the result, but otherwise it is
        equivalent.

        """
        # make sure expr is Expr if pattern is Expr
        from .expr import Add, Expr
        from sympy import Mul
        if isinstance(self, Expr) and not isinstance(expr, Expr):
            return None

        # handle simple patterns
        if self == expr:
            return repl_dict

        d = self._matches_simple(expr, repl_dict)
        if d is not None:
            return d

        # eliminate exact part from pattern: (2+a+w1+w2).matches(expr) -> (w1+w2).matches(expr-a-2)
        from .function import WildFunction
        from .symbol import Wild
        wild_part, exact_part = sift(self.args, lambda p:
            p.has(Wild, WildFunction) and not expr.has(p),
            binary=True)
        if not exact_part:
            wild_part = list(ordered(wild_part))
        else:
            exact = self._new_rawargs(*exact_part)
            free = expr.free_symbols
            if free and (exact.free_symbols - free):
                # there are symbols in the exact part that are not
                # in the expr; but if there are no free symbols, let
                # the matching continue
                return None
            newexpr = self._combine_inverse(expr, exact)
            if not old and (expr.is_Add or expr.is_Mul):
                if newexpr.count_ops() > expr.count_ops():
                    return None
            newpattern = self._new_rawargs(*wild_part)
            return newpattern.matches(newexpr, repl_dict)

        # now to real work ;)
        i = 0
        saw = set()
        while expr not in saw:
            saw.add(expr)
            expr_list = (self.identity,) + tuple(ordered(self.make_args(expr)))
            for last_op in reversed(expr_list):
                for w in reversed(wild_part):
                    d1 = w.matches(last_op, repl_dict)
                    if d1 is not None:
                        d2 = self.xreplace(d1).matches(expr, d1)
                        if d2 is not None:
                            return d2

            if i == 0:
                if self.is_Mul:
                    # make e**i look like Mul
                    if expr.is_Pow and expr.exp.is_Integer:
                        if expr.exp > 0:
                            expr = Mul(*[expr.base, expr.base**(expr.exp - 1)], evaluate=False)
                        else:
                            expr = Mul(*[1/expr.base, expr.base**(expr.exp + 1)], evaluate=False)
                        i += 1
                        continue

#.........这里部分代码省略.........
开发者ID:bjodah,项目名称:sympy,代码行数:101,代码来源:operations.py


示例18: piecewise_fold

def piecewise_fold(expr):
    """
    Takes an expression containing a piecewise function and returns the
    expression in piecewise form. In addition, any ITE conditions are
    rewritten in negation normal form and simplified.

    Examples
    ========

    >>> from sympy import Piecewise, piecewise_fold, sympify as S
    >>> from sympy.abc import x
    >>> p = Piecewise((x, x < 1), (1, S(1) <= x))
    >>> piecewise_fold(x*p)
    Piecewise((x**2, x < 1), (x, True))

    See Also
    ========

    Piecewise
    """
    if not isinstance(expr, Basic) or not expr.has(Piecewise):
        return expr

    new_args = []
    if isinstance(expr, (ExprCondPair, Piecewise)):
        for e, c in expr.args:
            if not isinstance(e, Piecewise):
                e = piecewise_fold(e)
            # we don't keep Piecewise in condition because
            # it has to be checked to see that it's complete
            # and we convert it to ITE at that time
            assert not c.has(Piecewise)  # pragma: no cover
            if isinstance(c, ITE):
                c = c.to_nnf()
                c = simplify_logic(c, form='cnf')
            if isinstance(e, Piecewise):
                new_args.extend([(piecewise_fold(ei), And(ci, c))
                    for ei, ci in e.args])
            else:
                new_args.append((e, c))
    else:
        from sympy.utilities.iterables import cartes, sift, common_prefix
        # Given
        #     P1 = Piecewise((e11, c1), (e12, c2), A)
        #     P2 = Piecewise((e21, c1), (e22, c2), B)
        #     ...
        # the folding of f(P1, P2) is trivially
        # Piecewise(
        #   (f(e11, e21), c1),
        #   (f(e12, e22), c2),
        #   (f(Piecewise(A), Piecewise(B)), True))
        # Certain objects end up rewriting themselves as thus, so
        # we do that grouping before the more generic folding.
        # The following applies this idea when f = Add or f = Mul
        # (and the expression is commutative).
        if expr.is_Add or expr.is_Mul and expr.is_commutative:
            p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
            pc = sift(p, lambda x: x.args[0].cond)
            for c in pc:
                if len(pc[c]) > 1:
                    pargs = [list(i.args) for i in pc[c]]
                    # the first one is the same; there may be more
                    com = common_prefix(*[
                        [i.cond for i in j] for j in pargs])
                    n = len(com)
                    collected = []
                    for i in range(n):
                        collected.append((
                            expr.func(*[ai[i].expr for ai in pargs]),
                            com[i]))
                    remains = []
                    for a in pargs:
                        if n == len(a):  # no more args
                            continue
                        if a[n].cond == True:  # no longer Piecewise
                            remains.append(a[n].expr)
                        else:  # restore the remaining Piecewise
                            remains.append(
                                Piecewise(*a[n:], evaluate=False))
                    if remains:
                        collected.append((expr.func(*remains), True))
                    args.append(Piecewise(*collected, evaluate=False))
                    continue
                args.extend(pc[c])
        else:
            args = expr.args
        # fold
        folded = list(map(piecewise_fold, args))
        for ec in cartes(*[
                (i.args if isinstance(i, Piecewise) else
                 [(i, true)]) for i in folded]):
            e, c = zip(*ec)
            new_args.append((expr.func(*e), And(*c)))

    return Piecewise(*new_args)
开发者ID:Lenqth,项目名称:sympy,代码行数:95,代码来源:piecewise.py


示例19: _sort_args

 def _sort_args(self, args):
     lists, atoms = sift(args,
         lambda a: isinstance(a, (tuple, list)), binary=True)
     return atoms, lists
开发者ID:bjodah,项目名称:sympy,代码行数:4,代码来源:color_scheme.py


示例20: short_entry

    # short entries will be ignored. The ORDER MATTERS
    # so don't re-order the lines for a given address.
    # Other tidying up could be done but we won't do that here.
    def short_entry(line):
        if line.count('<') == 2:
            if line.split('>', 1)[1].split('<')[0].strip():
                return False
        return True
    if len(who[k]) == 1:
        line = who[k][0]
        if not line.strip():
            continue  # ignore blank lines
        out.append(line)
    else:
        uniq = list(OrderedDict.fromkeys(who[k]))
        short, long = sift(uniq, short_entry, binary=True)
        out.extend(long)
        out.extend(short)

if out != lines or not blankline:
    # write lines
    with codecs.open(os.path.realpath(os.path.join(
            __file__, os.path.pardir, os.path.pardir, ".mailmap")),
            "w", "utf-8") as fd:
        fd.write('\n'.join(out))
        fd.write('\n')
    print()
    if out != lines:
        print(yellow('.mailmap lines were re-ordered.'))
    else:
        print(yellow('blank line added to end of .mailmap'))
开发者ID:oscarbenjamin,项目名称:sympy,代码行数:31,代码来源:mailmap_update.py



注:本文中的sympy.utilities.iterables.sift函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python iterables.subsets函数代码示例发布时间:2022-05-27
下一篇:
Python iterables.preorder_traversal函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap