当前位置: 首页>>代码示例>>Python>>正文


Python iterables.sift函数代码示例

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


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


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