本文整理汇总了Python中sympy.core.compatibility.ordered函数的典型用法代码示例。如果您正苦于以下问题:Python ordered函数的具体用法?Python ordered怎么用?Python ordered使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ordered函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_ordered
def test_ordered():
# Issue 7210 - this had been failing with python2/3 problems
assert list(ordered([{1: 3, 2: 4, 9: 10}, {1: 3}])) == [{1: 3}, {1: 3, 2: 4, 9: 10}]
# warnings should not be raised for identical items
l = [1, 1]
assert list(ordered(l, warn=True)) == l
l = [[1], [2], [1]]
assert list(ordered(l, warn=True)) == [[1], [1], [2]]
raises(ValueError, lambda: list(ordered(["a", "ab"], keys=[lambda x: x[0]], default=False, warn=True)))
示例2: intersection
def intersection(self, o):
"""The intersection of the parabola and another geometrical entity `o`.
Parameters
==========
o : GeometryEntity, LinearEntity
Returns
=======
intersection : list of GeometryEntity objects
Examples
========
>>> from sympy import Parabola, Point, Ellipse, Line, Segment
>>> p1 = Point(0,0)
>>> l1 = Line(Point(1, -2), Point(-1,-2))
>>> parabola1 = Parabola(p1, l1)
>>> parabola1.intersection(Ellipse(Point(0, 0), 2, 5))
[Point2D(-2, 0), Point2D(2, 0)]
>>> parabola1.intersection(Line(Point(-7, 3), Point(12, 3)))
[Point2D(-4, 3), Point2D(4, 3)]
>>> parabola1.intersection(Segment((-12, -65), (14, -68)))
[]
"""
x, y = symbols('x y', real=True)
parabola_eq = self.equation()
if isinstance(o, Parabola):
if o in self:
return [o]
else:
return list(ordered([Point(i) for i in solve([parabola_eq, o.equation()], [x, y])]))
elif isinstance(o, Point2D):
if simplify(parabola_eq.subs(([(x, o._args[0]), (y, o._args[1])]))) == 0:
return [o]
else:
return []
elif isinstance(o, (Segment2D, Ray2D)):
result = solve([parabola_eq, Line2D(o.points[0], o.points[1]).equation()], [x, y])
return list(ordered([Point2D(i) for i in result if i in o]))
elif isinstance(o, (Line2D, Ellipse)):
return list(ordered([Point2D(i) for i in solve([parabola_eq, o.equation()], [x, y])]))
elif isinstance(o, LinearEntity3D):
raise TypeError('Entity must be two dimensional, not three dimensional')
else:
raise TypeError('Wrong type of argument were put')
示例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
示例4: __new__
def __new__(cls, *args, **kwargs):
argset = set([])
obj = super(Xor, cls).__new__(cls, *args, **kwargs)
for arg in obj._args:
if isinstance(arg, Number) or arg in (True, False):
if arg:
arg = true
else:
continue
if isinstance(arg, Xor):
for a in arg.args:
argset.remove(a) if a in argset else argset.add(a)
elif arg in argset:
argset.remove(arg)
else:
argset.add(arg)
if len(argset) == 0:
return false
elif len(argset) == 1:
return argset.pop()
elif True in argset:
argset.remove(True)
return Not(Xor(*argset))
else:
obj._args = tuple(ordered(argset))
obj._argset = frozenset(argset)
return obj
示例5: __new__
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_evaluate[0])
# flatten inputs to merge intersections and iterables
args = list(args)
def flatten(arg):
if isinstance(arg, Set):
if arg.is_Intersection:
return sum(map(flatten, arg.args), [])
else:
return [arg]
if iterable(arg): # and not isinstance(arg, Set) (implicit)
return sum(map(flatten, arg), [])
raise TypeError("Input must be Sets or iterables of Sets")
args = flatten(args)
if len(args) == 0:
raise TypeError("Intersection expected at least one argument")
# Reduce sets using known rules
if evaluate:
return Intersection.reduce(args)
args = list(ordered(args, Set._infimum_key))
return Basic.__new__(cls, *args)
示例6: roots_cyclotomic
def roots_cyclotomic(f, factor=False):
"""Compute roots of cyclotomic polynomials. """
L, U = _inv_totient_estimate(f.degree())
for n in range(L, U + 1):
g = cyclotomic_poly(n, f.gen, polys=True)
if f == g:
break
else: # pragma: no cover
raise RuntimeError("failed to find index of a cyclotomic polynomial")
roots = []
if not factor:
# get the indices in the right order so the computed
# roots will be sorted
h = n//2
ks = [i for i in range(1, n + 1) if igcd(i, n) == 1]
ks.sort(key=lambda x: (x, -1) if x <= h else (abs(x - n), 1))
d = 2*I*pi/n
for k in reversed(ks):
roots.append(exp(k*d).expand(complex=True))
else:
g = Poly(f, extension=root(-1, n))
for h, _ in ordered(g.factor_list()[1]):
roots.append(-h.TC())
return roots
示例7: _mostfunc
def _mostfunc(lhs, func, X=None):
"""Returns the term in lhs which contains the most of the
func-type things e.g. log(log(x)) wins over log(x) if both terms appear.
``func`` can be a function (exp, log, etc...) or any other SymPy object,
like Pow.
Examples
========
>>> from sympy.solvers.bivariate import _mostfunc
>>> from sympy.functions.elementary.exponential import exp
>>> from sympy.utilities.pytest import raises
>>> from sympy.abc import x, y
>>> _mostfunc(exp(x) + exp(exp(x) + 2), exp)
exp(exp(x) + 2)
>>> _mostfunc(exp(x) + exp(exp(y) + 2), exp, x)
exp(x)
>>> _mostfunc(exp(x) + exp(exp(y) + 2), exp, x)
exp(x)
>>> _mostfunc(x, exp, x) is None
True
>>> _mostfunc(exp(x) + exp(x*y), exp, x)
exp(x)
"""
fterms = [tmp for tmp in lhs.atoms(func) if (not X or
X.is_Symbol and X in tmp.free_symbols or
not X.is_Symbol and tmp.has(X))]
if len(fterms) == 1:
return fterms[0]
elif fterms:
return max(list(ordered(fterms)), key=lambda x: x.count(func))
return None
示例8: _refine_imaginary
def _refine_imaginary(cls, complexes):
sifted = sift(complexes, lambda c: c[1])
complexes = []
for f in ordered(sifted):
nimag = _imag_count_of_factor(f)
if nimag == 0:
# refine until xbounds are neg or pos
for u, f, k in sifted[f]:
while u.ax*u.bx <= 0:
u = u._inner_refine()
complexes.append((u, f, k))
else:
# refine until all but nimag xbounds are neg or pos
potential_imag = list(range(len(sifted[f])))
while True:
assert len(potential_imag) > 1
for i in list(potential_imag):
u, f, k = sifted[f][i]
if u.ax*u.bx > 0:
potential_imag.remove(i)
elif u.ax != u.bx:
u = u._inner_refine()
sifted[f][i] = u, f, k
if len(potential_imag) == nimag:
break
complexes.extend(sifted[f])
return complexes
示例9: __new__
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get("evaluate", global_evaluate[0])
# flatten inputs
args = list(args)
# adapted from sympy.sets.sets.Union
def _flatten(arg):
if isinstance(arg, SeqBase):
if isinstance(arg, SeqMul):
return sum(map(_flatten, arg.args), [])
else:
return [arg]
elif iterable(arg):
return sum(map(_flatten, arg), [])
raise TypeError("Input must be Sequences or " " iterables of Sequences")
args = _flatten(args)
# Multiplication of no sequences is EmptySequence
if not args:
return S.EmptySequence
if Intersection(a.interval for a in args) is S.EmptySet:
return S.EmptySequence
# reduce using known rules
if evaluate:
return SeqMul.reduce(args)
args = list(ordered(args, SeqBase._start_key))
return Basic.__new__(cls, *args)
示例10: random_symbols
def random_symbols(expr):
"""
Returns a sorted list of all RandomSymbols within a SymPy Expression.
"""
try:
return list(ordered(expr.atoms(RandomSymbol), warn=True))
except AttributeError:
return []
示例11: _preorder_traversal
def _preorder_traversal(self, node, keys):
yield node
if self._skip_flag:
self._skip_flag = False
return
if isinstance(node, Basic):
args = node.args
if keys:
if keys != True:
args = ordered(args, keys, default=False)
else:
args = ordered(args)
for arg in args:
for subtree in self._preorder_traversal(arg, keys):
yield subtree
elif iterable(node):
for item in node:
for subtree in self._preorder_traversal(item, keys):
yield subtree
示例12: __new__
def __new__(cls, *args, **kwargs):
argset = set([])
obj = super(Xor, cls).__new__(cls, *args, **kwargs)
for arg in obj._args:
if isinstance(arg, Number) or arg in (True, False):
if arg:
arg = true
else:
continue
if isinstance(arg, Xor):
for a in arg.args:
argset.remove(a) if a in argset else argset.add(a)
elif arg in argset:
argset.remove(arg)
else:
argset.add(arg)
rel = [(r, r.canonical, (~r).canonical) for r in argset if r.is_Relational]
odd = False # is number of complimentary pairs odd? start 0 -> False
remove = []
for i, (r, c, nc) in enumerate(rel):
for j in range(i + 1, len(rel)):
rj, cj = rel[j][:2]
if cj == nc:
odd = ~odd
break
elif cj == c:
break
else:
continue
remove.append((r, rj))
if odd:
argset.remove(true) if true in argset else argset.add(true)
for a, b in remove:
argset.remove(a)
argset.remove(b)
if len(argset) == 0:
return false
elif len(argset) == 1:
return argset.pop()
elif True in argset:
argset.remove(True)
return Not(Xor(*argset))
else:
obj._args = tuple(ordered(argset))
obj._argset = frozenset(argset)
return obj
示例13: _get_complexes
def _get_complexes(cls, factors, use_cache=True):
"""Compute complex root isolating intervals for a list of factors. """
complexes = []
for factor, k in ordered(factors):
try:
if not use_cache:
raise KeyError
c = _complexes_cache[factor]
complexes.extend([(i, factor, k) for i in c])
except KeyError:
complex_part = cls._get_complexes_sqf(factor, use_cache)
new = [(root, factor, k) for root in complex_part]
complexes.extend(new)
complexes = cls._complexes_sorted(complexes)
return complexes
示例14: __new__
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_evaluate[0])
if evaluate:
if len(args) == 1 and iterable(args[0]):
args = args[0]
args = list(map(sympify, args))
if len(args) == 0:
return EmptySet()
else:
args = list(map(sympify, args))
args = list(ordered(frozenset(args)))
obj = Basic.__new__(cls, *args)
obj._elements = frozenset(args)
return obj
示例15: root_factors
def root_factors(f, *gens, **args):
"""
Returns all factors of a univariate polynomial.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.polys.polyroots import root_factors
>>> root_factors(x**2 - y, x)
[x - sqrt(y), x + sqrt(y)]
"""
args = dict(args)
filter = args.pop('filter', None)
F = Poly(f, *gens, **args)
if not F.is_Poly:
return [f]
if F.is_multivariate:
raise ValueError('multivariate polynomials are not supported')
x = F.gens[0]
zeros = roots(F, filter=filter)
if not zeros:
factors = [F]
else:
factors, N = [], 0
for r, n in ordered(zeros.items()):
factors, N = factors + [Poly(x - r, x)]*n, N + n
if N < F.degree():
G = reduce(lambda p, q: p*q, factors)
factors.append(F.quo(G))
if not isinstance(f, Poly):
factors = [ f.as_expr() for f in factors ]
return factors