本文整理汇总了Python中sympy.core.compatibility.iterable函数的典型用法代码示例。如果您正苦于以下问题:Python iterable函数的具体用法?Python iterable怎么用?Python iterable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iterable函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: doprint
def doprint(self, funcname, args, expr):
"""Returns the function definition code as a string."""
from sympy import Dummy
funcbody = []
if not iterable(args):
args = [args]
argstrs, expr = self._preprocess(args, expr)
# Generate argument unpacking and final argument list
funcargs = []
unpackings = []
for argstr in argstrs:
if iterable(argstr):
funcargs.append(self._argrepr(Dummy()))
unpackings.extend(self._print_unpacking(argstr, funcargs[-1]))
else:
funcargs.append(argstr)
funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs))
# Wrap input arguments before unpacking
funcbody.extend(self._print_funcargwrapping(funcargs))
funcbody.extend(unpackings)
funcbody.append('return ({})'.format(self._exprrepr(expr)))
funclines = [funcsig]
funclines.extend(' ' + line for line in funcbody)
return '\n'.join(funclines) + '\n'
开发者ID:cmarqu,项目名称:sympy,代码行数:35,代码来源:lambdify.py
示例2: reduce_inequalities
def reduce_inequalities(inequalities, symbols=[]):
"""Reduce a system of inequalities with rational coefficients.
Examples
========
>>> from sympy import sympify as S, Symbol
>>> from sympy.abc import x, y
>>> from sympy.solvers.inequalities import reduce_inequalities
>>> reduce_inequalities(0 <= x + 3, [])
And(-3 <= x, x < oo)
>>> reduce_inequalities(0 <= x + y*2 - 1, [x])
x >= -2*y + 1
"""
if not iterable(inequalities):
inequalities = [inequalities]
inequalities = [sympify(i) for i in inequalities]
gens = set().union(*[i.free_symbols for i in inequalities])
if not iterable(symbols):
symbols = [symbols]
symbols = (set(symbols) or gens) & gens
if any(i.is_real is False for i in symbols):
raise TypeError(
filldedent(
"""
inequalities cannot contain symbols that are not real."""
)
)
# make vanilla symbol real
recast = dict([(i, Dummy(i.name, real=True)) for i in gens if i.is_real is None])
inequalities = [i.xreplace(recast) for i in inequalities]
symbols = set([i.xreplace(recast) for i in symbols])
# prefilter
keep = []
for i in inequalities:
if isinstance(i, Relational):
i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0)
elif i not in (True, False):
i = Eq(i, 0)
if i == True:
continue
elif i == False:
return S.false
if i.lhs.is_number:
raise NotImplementedError("could not determine truth value of %s" % i)
keep.append(i)
inequalities = keep
del keep
# solve system
rv = _reduce_inequalities(inequalities, symbols)
# restore original symbols and return
return rv.xreplace(dict([(v, k) for k, v in recast.items()]))
开发者ID:MooVI,项目名称:sympy,代码行数:60,代码来源:inequalities.py
示例3: test_iterable_ordered_iter
def test_iterable_ordered_iter():
ordered = [list(), tuple(), Tuple(), Matrix([[]])]
unordered = [set()]
not_sympy_iterable = [{}, '']
assert all(ordered_iter(i) for i in ordered)
assert all(not ordered_iter(i) for i in unordered)
assert all(iterable(i) for i in ordered + unordered)
assert all(not iterable(i) for i in not_sympy_iterable)
assert all(iterable(i, exclude=None) for i in not_sympy_iterable)
开发者ID:wxgeo,项目名称:sympy,代码行数:9,代码来源:test_containers.py
示例4: test_iterable_is_sequence
def test_iterable_is_sequence():
ordered = [list(), tuple(), Tuple(), Matrix([[]])]
unordered = [set()]
not_sympy_iterable = [{}, '', u('')]
assert all(is_sequence(i) for i in ordered)
assert all(not is_sequence(i) for i in unordered)
assert all(iterable(i) for i in ordered + unordered)
assert all(not iterable(i) for i in not_sympy_iterable)
assert all(iterable(i, exclude=None) for i in not_sympy_iterable)
开发者ID:AdrianPotter,项目名称:sympy,代码行数:9,代码来源:test_containers.py
示例5: test_iterable
def test_iterable():
assert iterable(0) is False
assert iterable(1) is False
assert iterable(None) is False
class Test1(NotIterable):
pass
assert iterable(Test1()) is False
class Test2(NotIterable):
_iterable = True
assert iterable(Test2()) is True
class Test3(object):
pass
assert iterable(Test3()) is False
class Test4(object):
_iterable = True
assert iterable(Test4()) is True
class Test5(object):
def __iter__(self):
yield 1
assert iterable(Test5()) is True
class Test6(Test5):
_iterable = False
assert iterable(Test6()) is False
开发者ID:asmeurer,项目名称:sympy,代码行数:35,代码来源:test_compatibility.py
示例6: is_sequence
def is_sequence(i, include=None):
"""
Return a boolean indicating whether ``i`` is a sequence in the SymPy
sense. If anything that fails the test below should be included as
being a sequence for your application, set 'include' to that object's
type; multiple types should be passed as a tuple of types.
Note: although generators can generate a sequence, they often need special
handling to make sure their elements are captured before the generator is
exhausted, so these are not included by default in the definition of a
sequence.
See also: iterable
Examples
========
>>> from sympy.utilities.iterables import is_sequence
>>> from types import GeneratorType
>>> is_sequence([])
True
>>> is_sequence(set())
False
>>> is_sequence('abc')
False
>>> is_sequence('abc', include=str)
True
>>> generator = (c for c in 'abc')
>>> is_sequence(generator)
False
>>> is_sequence(generator, include=(str, GeneratorType))
True
"""
return hasattr(i, "__getitem__") and iterable(i) or bool(include) and isinstance(i, include)
开发者ID:haraldschilly,项目名称:sympy,代码行数:35,代码来源:compatibility.py
示例7: fuzzy_and
def fuzzy_and(*args):
"""Return True (all True), False (any False) or None.
If `a` is an iterable it must have more than one element."""
if (len(args) == 1 and iterable(args[0]) or
len(args) > 2):
if len(args) == 1:
args = args[0]
rv = True
i = 0
for ai in args:
ai = fuzzy_bool(ai)
if ai is False:
return False
if rv: # this will stop updating if a None is ever trapped
rv = ai
i += 1
if i < 2:
raise ValueError('iterables must have 2 or more elements')
return rv
a, b = [fuzzy_bool(i) for i in args]
if a is True and b is True:
return True
elif a is False or b is False:
return False
开发者ID:wxgeo,项目名称:sympy,代码行数:27,代码来源:logic.py
示例8: _find_opts
def _find_opts(expr):
if expr.is_Atom or expr.is_Order:
return
if iterable(expr):
list(map(_find_opts, expr))
return
if expr in seen_subexp:
return expr
seen_subexp.add(expr)
list(map(_find_opts, expr.args))
if _coeff_isneg(expr):
neg_expr = -expr
if not neg_expr.is_Atom:
opt_subs[expr] = Mul(S.NegativeOne, neg_expr, evaluate=False)
seen_subexp.add(neg_expr)
expr = neg_expr
if expr.is_Mul:
muls.add(expr)
elif expr.is_Add:
adds.add(expr)
elif expr.is_Pow:
if _coeff_isneg(expr.exp):
opt_subs[expr] = Pow(Pow(expr.base, -expr.exp), S.NegativeOne,
evaluate=False)
开发者ID:B-Rich,项目名称:sympy,代码行数:32,代码来源:cse_main.py
示例9: _find_repeated
def _find_repeated(expr):
if not isinstance(expr, Basic):
return
if expr.is_Atom or expr.is_Order:
return
if iterable(expr):
args = expr
else:
if expr in seen_subexp:
for ign in ignore:
if ign in expr.free_symbols:
break
else:
to_eliminate.add(expr)
return
seen_subexp.add(expr)
if expr in opt_subs:
expr = opt_subs[expr]
args = expr.args
list(map(_find_repeated, args))
开发者ID:chaffra,项目名称:sympy,代码行数:27,代码来源:cse_main.py
示例10: _find_opts
def _find_opts(expr):
if not isinstance(expr, Basic):
return
if expr.is_Atom or expr.is_Order:
return
if iterable(expr):
list(map(_find_opts, expr))
return
if expr in seen_subexp:
return expr
seen_subexp.add(expr)
list(map(_find_opts, expr.args))
if _coeff_isneg(expr):
neg_expr = -expr
if not neg_expr.is_Atom:
opt_subs[expr] = Mul(S.NegativeOne, neg_expr, evaluate=False)
seen_subexp.add(neg_expr)
expr = neg_expr
if isinstance(expr, (Mul, MatMul)):
muls.add(expr)
elif isinstance(expr, (Add, MatAdd)):
adds.add(expr)
elif isinstance(expr, (Pow, MatPow)):
if _coeff_isneg(expr.exp):
opt_subs[expr] = Pow(Pow(expr.base, -expr.exp), S.NegativeOne,
evaluate=False)
开发者ID:chaffra,项目名称:sympy,代码行数:35,代码来源:cse_main.py
示例11: convert
def convert(self, elem, M=None):
"""
Convert ``elem`` into the internal representation.
This method is called implicitly whenever computations involve elements
not in the internal representation.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> F = QQ.old_poly_ring(x).free_module(2)
>>> F.convert([1, 0])
[1, 0]
"""
if isinstance(elem, FreeModuleElement):
if elem.module is self:
return elem
if elem.module.rank != self.rank:
raise CoercionFailed
return FreeModuleElement(self,
tuple(self.ring.convert(x, elem.module.ring) for x in elem.data))
elif iterable(elem):
tpl = tuple(self.ring.convert(x) for x in elem)
if len(tpl) != self.rank:
raise CoercionFailed
return FreeModuleElement(self, tpl)
elif elem is 0:
return FreeModuleElement(self, (self.ring.convert(0),)*self.rank)
else:
raise CoercionFailed
开发者ID:abhi98khandelwal,项目名称:sympy,代码行数:29,代码来源:modules.py
示例12: _walsh_hadamard_transform
def _walsh_hadamard_transform(seq, inverse=False):
"""Utility function for the Walsh Hadamard Transform"""
if not iterable(seq):
raise TypeError("Expected a sequence of coefficients "
"for Walsh Hadamard Transform")
a = [sympify(arg) for arg in seq]
n = len(a)
if n < 2:
return a
if n&(n - 1):
n = 2**n.bit_length()
a += [S.Zero]*(n - len(a))
h = 2
while h <= n:
hf, ut = h // 2, n // h
for i in range(0, n, h):
for j in range(hf):
u, v = a[i + j], a[i + j + hf]
a[i + j], a[i + j + hf] = u + v, u - v
h *= 2
if inverse:
a = [x/n for x in a]
return a
开发者ID:normalhuman,项目名称:sympy,代码行数:29,代码来源:transforms.py
示例13: _preprocess
def _preprocess(self, args, expr):
"""Preprocess args, expr to replace arguments that do not map
to valid Python identifiers.
Returns string form of args, and updated expr.
"""
from sympy import Dummy, Function, flatten, Derivative, ordered, Basic
from sympy.matrices import DeferredVector
# Args of type Dummy can cause name collisions with args
# of type Symbol. Force dummify of everything in this
# situation.
dummify = self._dummify or any(
isinstance(arg, Dummy) for arg in flatten(args))
argstrs = [None]*len(args)
for arg, i in reversed(list(ordered(zip(args, range(len(args)))))):
if iterable(arg):
s, expr = self._preprocess(arg, expr)
elif isinstance(arg, DeferredVector):
s = str(arg)
elif isinstance(arg, Basic) and arg.is_symbol:
s = self._argrepr(arg)
if dummify or not self._is_safe_ident(s):
dummy = Dummy()
s = self._argrepr(dummy)
expr = self._subexpr(expr, {arg: dummy})
elif dummify or isinstance(arg, (Function, Derivative)):
dummy = Dummy()
s = self._argrepr(dummy)
expr = self._subexpr(expr, {arg: dummy})
else:
s = str(arg)
argstrs[i] = s
return argstrs, expr
开发者ID:cmarqu,项目名称:sympy,代码行数:35,代码来源:lambdify.py
示例14: __new__
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_evaluate[0])
if iterable(args[0]):
if isinstance(args[0], Point) and not evaluate:
return args[0]
args = args[0]
# unpack the arguments into a friendly Tuple
# if we were already a Point, we're doing an excess
# iteration, but we'll worry about efficiency later
coords = Tuple(*args)
if any(a.is_number and im(a) for a in coords):
raise ValueError('Imaginary coordinates not permitted.')
# Turn any Floats into rationals and simplify
# any expressions before we instantiate
if evaluate:
coords = coords.xreplace(dict(
[(f, simplify(nsimplify(f, rational=True)))
for f in coords.atoms(Float)]))
if len(coords) == 2:
return Point2D(coords, **kwargs)
if len(coords) == 3:
return Point3D(coords, **kwargs)
return GeometryEntity.__new__(cls, *coords)
开发者ID:peterstangl,项目名称:sympy,代码行数:27,代码来源:point.py
示例15: lambdastr
def lambdastr(args, expr, printer=None):
"""
Returns a string that can be evaluated to a lambda function.
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import lambdastr
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'
"""
if printer is not None:
if inspect.isfunction(printer):
lambdarepr = printer
else:
if inspect.isclass(printer):
lambdarepr = lambda expr: printer().doprint(expr)
else:
lambdarepr = lambda expr: printer.doprint(expr)
else:
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import lambdarepr
# Transform everything to strings.
from sympy.matrices import DeferredVector
expr = lambdarepr(expr)
if isinstance(args, str):
pass
elif iterable(args, exclude=DeferredVector):
args = ",".join(str(a) for a in args)
else:
args = str(args)
return "lambda %s: (%s)" % (args, expr)
开发者ID:Acebulf,项目名称:sympy,代码行数:35,代码来源:lambdify.py
示例16: sub_args
def sub_args(args, dummies_dict):
if isinstance(args, str):
return args
elif isinstance(args, DeferredVector):
return str(args)
elif iterable(args):
flatten = lambda *n: (e for a in n for e in
(flatten(*a) if iterable(a) else (a,)))
dummies = flatten([sub_args(a, dummies_dict) for a in args])
return ",".join(str(a) for a in dummies)
else:
if isinstance(args, Function):
dummies = Dummy()
dummies_dict.update({args : dummies})
return str(dummies)
else:
return str(args)
开发者ID:Frifon,项目名称:sympy,代码行数:17,代码来源:lambdify.py
示例17: flatten
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")
开发者ID:alphaitis,项目名称:sympy,代码行数:9,代码来源:sets.py
示例18: _flatten
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")
开发者ID:LuckyStrikes1090,项目名称:sympy,代码行数:9,代码来源:sequences.py
示例19: group_to_finiteset
def group_to_finiteset(group):
"""
Converts ``group`` to a :class:``FiniteSet`` if it is an
iterable.
"""
if iterable(group):
return FiniteSet(group)
else:
return group
开发者ID:Vance-Turner,项目名称:sympy,代码行数:9,代码来源:diagram_drawing.py
示例20: posify
def posify(eq):
"""Return eq (with generic symbols made positive) and a
dictionary containing the mapping between the old and new
symbols.
Any symbol that has positive=None will be replaced with a positive dummy
symbol having the same name. This replacement will allow more symbolic
processing of expressions, especially those involving powers and
logarithms.
A dictionary that can be sent to subs to restore eq to its original
symbols is also returned.
>>> from sympy import posify, Symbol, log, solve
>>> from sympy.abc import x
>>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True))
(_x + n + p, {_x: x})
>>> eq = 1/x
>>> log(eq).expand()
log(1/x)
>>> log(posify(eq)[0]).expand()
-log(_x)
>>> p, rep = posify(eq)
>>> log(p).expand().subs(rep)
-log(x)
It is possible to apply the same transformations to an iterable
of expressions:
>>> eq = x**2 - 4
>>> solve(eq, x)
[-2, 2]
>>> eq_x, reps = posify([eq, x]); eq_x
[_x**2 - 4, _x]
>>> solve(*eq_x)
[2]
"""
eq = sympify(eq)
if iterable(eq):
f = type(eq)
eq = list(eq)
syms = set()
for e in eq:
syms = syms.union(e.atoms(Symbol))
reps = {}
for s in syms:
reps.update(dict((v, k) for k, v in posify(s)[1].items()))
for i, e in enumerate(eq):
eq[i] = e.subs(reps)
return f(eq), dict([(r, s) for s, r in reps.items()])
reps = dict([(s, Dummy(s.name, positive=True))
for s in eq.free_symbols if s.is_positive is None])
eq = eq.subs(reps)
return eq, dict([(r, s) for s, r in reps.items()])
开发者ID:ZachPhillipsGary,项目名称:CS200-NLP-ANNsProject,代码行数:56,代码来源:simplify.py
注:本文中的sympy.core.compatibility.iterable函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论