本文整理汇总了Python中sympy.core.compatibility.iterable函数的典型用法代码示例。如果您正苦于以下问题:Python iterable函数的具体用法?Python iterable怎么用?Python iterable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iterable函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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'
示例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()]))
示例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)
示例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)
示例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
示例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)
示例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
示例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)
示例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))
示例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)
示例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
示例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
示例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
示例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)
示例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)